• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

tstack / lnav / 18736722727-2602

23 Oct 2025 03:35AM UTC coverage: 69.333% (-0.7%) from 70.006%
18736722727-2602

push

github

tstack
[tests] update expected output

50430 of 72736 relevant lines covered (69.33%)

425990.7 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

82.42
/src/command_executor.cc
1
/**
2
 * Copyright (c) 2015, Timothy Stack
3
 *
4
 * All rights reserved.
5
 *
6
 * Redistribution and use in source and binary forms, with or without
7
 * modification, are permitted provided that the following conditions are met:
8
 *
9
 * * Redistributions of source code must retain the above copyright notice, this
10
 * list of conditions and the following disclaimer.
11
 * * Redistributions in binary form must reproduce the above copyright notice,
12
 * this list of conditions and the following disclaimer in the documentation
13
 * and/or other materials provided with the distribution.
14
 * * Neither the name of Timothy Stack nor the names of its contributors
15
 * may be used to endorse or promote products derived from this software
16
 * without specific prior written permission.
17
 *
18
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND ANY
19
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21
 * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
22
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
25
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
 */
29

30
#include <vector>
31

32
#include "command_executor.hh"
33

34
#include "base/ansi_scrubber.hh"
35
#include "base/ansi_vars.hh"
36
#include "base/fs_util.hh"
37
#include "base/humanize.hh"
38
#include "base/injector.hh"
39
#include "base/itertools.hh"
40
#include "base/paths.hh"
41
#include "base/string_util.hh"
42
#include "bound_tags.hh"
43
#include "breadcrumb_curses.hh"
44
#include "config.h"
45
#include "curl_looper.hh"
46
#include "db_sub_source.hh"
47
#include "help_text_formatter.hh"
48
#include "lnav.hh"
49
#include "lnav.indexing.hh"
50
#include "lnav.prompt.hh"
51
#include "lnav_config.hh"
52
#include "lnav_util.hh"
53
#include "log_format_loader.hh"
54
#include "prql-modules.h"
55
#include "readline_highlighters.hh"
56
#include "service_tags.hh"
57
#include "shlex.hh"
58
#include "sql_help.hh"
59
#include "sql_util.hh"
60
#include "vtab_module.hh"
61

62
#ifdef HAVE_RUST_DEPS
63
#    include "lnav_rs_ext.cxx.hh"
64
#endif
65

66
using namespace std::literals::chrono_literals;
67
using namespace lnav::roles::literals;
68

69
exec_context INIT_EXEC_CONTEXT;
70

71
static sig_atomic_t sql_counter = 0;
72

73
int
74
sql_progress(const log_cursor& lc)
11,749✔
75
{
76
    if (lnav_data.ld_window == nullptr) {
11,749✔
77
        return 0;
11,743✔
78
    }
79

80
    if (!lnav_data.ld_looping) {
6✔
81
        return 1;
×
82
    }
83

84
    if (ui_periodic_timer::singleton().time_to_update(sql_counter)) {
6✔
85
        auto* breadcrumb_view = injector::get<breadcrumb_curses*>();
6✔
86
        breadcrumb_view->set_enabled(false);
6✔
87
        lnav_data.ld_status[LNS_TOP].set_enabled(false);
6✔
88
        lnav_data.ld_view_stack.top() |
6✔
89
            [](auto* tc) { tc->set_enabled(false); };
3✔
90
        ssize_t total = lnav_data.ld_log_source.text_line_count();
6✔
91
        off_t off = lc.lc_curr_line;
6✔
92

93
        if (off >= 0 && off <= total) {
6✔
94
            lnav_data.ld_bottom_source.update_loading(off, total);
6✔
95
            lnav_data.ld_status[LNS_BOTTOM].set_needs_update();
6✔
96
        }
97
        lnav::prompt::get().p_editor.clear_alt_value();
6✔
98
        auto refresh_res
99
            = lnav_data.ld_status_refresher(lnav::func::op_type::blocking);
6✔
100
        if (refresh_res == lnav::progress_result_t::interrupt) {
6✔
101
            return 1;
×
102
        }
103
    }
104

105
    return 0;
6✔
106
}
107

108
void
109
sql_progress_finished()
1,674✔
110
{
111
    if (sql_counter == 0) {
1,674✔
112
        return;
1,668✔
113
    }
114

115
    sql_counter = 0;
6✔
116

117
    if (lnav_data.ld_window == nullptr) {
6✔
118
        return;
×
119
    }
120

121
    auto* breadcrumb_view = injector::get<breadcrumb_curses*>();
6✔
122
    breadcrumb_view->set_enabled(true);
6✔
123
    lnav_data.ld_status[LNS_TOP].set_enabled(true);
6✔
124
    lnav_data.ld_view_stack.top() | [](auto* tc) { tc->set_enabled(true); };
9✔
125
    lnav_data.ld_bottom_source.update_loading(0, 0);
6✔
126
    lnav_data.ld_status[LNS_BOTTOM].set_needs_update();
6✔
127
    lnav_data.ld_status_refresher(lnav::func::op_type::blocking);
6✔
128
    lnav_data.ld_views[LNV_DB].redo_search();
6✔
129
}
130

131
static Result<std::string, lnav::console::user_message> execute_from_file(
132
    exec_context& ec,
133
    const std::string& src,
134
    int line_number,
135
    const std::string& cmdline);
136

137
Result<std::string, lnav::console::user_message>
138
execute_command(exec_context& ec, const std::string& cmdline)
707✔
139
{
140
    static auto op = lnav_operation{__FUNCTION__};
707✔
141

142
    auto op_guard = lnav_opid_guard::internal(op);
707✔
143
    std::vector<std::string> args;
707✔
144

145
    log_info("Executing command: %s", cmdline.c_str());
707✔
146

147
    split_ws(cmdline, args);
707✔
148

149
    if (!args.empty()) {
707✔
150
        readline_context::command_map_t::iterator iter;
707✔
151

152
        if ((iter = lnav_commands.find(args[0])) == lnav_commands.end()) {
707✔
153
            return ec.make_error("unknown command - {}", args[0]);
×
154
        }
155

156
        ec.ec_current_help = &iter->second->c_help;
707✔
157
        try {
158
            auto retval = iter->second->c_func(ec, cmdline, args);
707✔
159
            if (retval.isErr()) {
707✔
160
                auto um = retval.unwrapErr();
43✔
161

162
                ec.add_error_context(um);
43✔
163
                ec.ec_current_help = nullptr;
43✔
164
                return Err(um);
43✔
165
            }
43✔
166
            ec.ec_current_help = nullptr;
664✔
167

168
            return retval;
664✔
169
        } catch (const std::exception& e) {
707✔
170
            auto um = lnav::console::user_message::error(
×
171
                          attr_line_t("unexpected error while executing: ")
×
172
                              .append(lnav::roles::quoted_code(cmdline)))
×
173
                          .with_reason(e.what());
×
174
            return Err(um);
×
175
        }
×
176
    }
177

178
    return ec.make_error("no command to execute");
×
179
}
707✔
180

181
static Result<std::map<std::string, scoped_value_t>,
182
              lnav::console::user_message>
183
bind_sql_parameters(exec_context& ec, sqlite3_stmt* stmt)
1,667✔
184
{
185
    std::map<std::string, scoped_value_t> retval;
1,667✔
186
    auto param_count = sqlite3_bind_parameter_count(stmt);
1,667✔
187
    for (int lpc = 0; lpc < param_count; lpc++) {
1,856✔
188
        std::map<std::string, std::string>::iterator ov_iter;
190✔
189
        const auto* name = sqlite3_bind_parameter_name(stmt, lpc + 1);
190✔
190
        if (name == nullptr) {
190✔
191
            auto um
192
                = lnav::console::user_message::error("invalid SQL statement")
2✔
193
                      .with_reason(
2✔
194
                          "using a question-mark (?) for bound variables "
195
                          "is not supported, only named bound parameters "
196
                          "are supported")
197
                      .with_help(
2✔
198
                          "named parameters start with a dollar-sign "
199
                          "($) or colon (:) followed by the variable name")
200
                      .move();
1✔
201
            ec.add_error_context(um);
1✔
202

203
            return Err(um);
1✔
204
        }
1✔
205

206
        if (name[0] == '$') {
189✔
207
            const auto& lvars = ec.ec_local_vars.top();
160✔
208
            const auto& gvars = ec.ec_global_vars;
160✔
209
            std::map<std::string, scoped_value_t>::const_iterator local_var,
160✔
210
                global_var;
160✔
211
            const char* env_value;
212

213
            if (lnav_data.ld_window) {
160✔
214
                char buf[32];
215
                unsigned int lines, cols;
216

217
                ncplane_dim_yx(lnav_data.ld_window, &lines, &cols);
27✔
218
                if (strcmp(name, "$LINES") == 0) {
27✔
219
                    snprintf(buf, sizeof(buf), "%d", lines);
×
220
                    sqlite3_bind_text(stmt, lpc + 1, buf, -1, SQLITE_TRANSIENT);
×
221
                } else if (strcmp(name, "$COLS") == 0) {
27✔
222
                    snprintf(buf, sizeof(buf), "%d", cols);
×
223
                    sqlite3_bind_text(stmt, lpc + 1, buf, -1, SQLITE_TRANSIENT);
×
224
                }
225
            }
226

227
            if ((local_var = lvars.find(&name[1])) != lvars.end()) {
480✔
228
                mapbox::util::apply_visitor(
134✔
229
                    sqlitepp::bind_visitor(stmt, lpc + 1), local_var->second);
134✔
230
                retval[name] = local_var->second;
402✔
231
            } else if ((global_var = gvars.find(&name[1])) != gvars.end()) {
78✔
232
                mapbox::util::apply_visitor(
9✔
233
                    sqlitepp::bind_visitor(stmt, lpc + 1), global_var->second);
9✔
234
                retval[name] = global_var->second;
27✔
235
            } else if ((env_value = getenv(&name[1])) != nullptr) {
17✔
236
                sqlite3_bind_text(stmt, lpc + 1, env_value, -1, SQLITE_STATIC);
3✔
237
                retval[name] = string_fragment::from_c_str(env_value);
9✔
238
            }
239
        } else if (name[0] == ':' && ec.ec_line_values != nullptr) {
29✔
240
            for (auto& lv : ec.ec_line_values->lvv_values) {
159✔
241
                if (lv.lv_meta.lvm_name != &name[1]) {
130✔
242
                    continue;
101✔
243
                }
244
                switch (lv.lv_meta.lvm_kind) {
29✔
245
                    case value_kind_t::VALUE_BOOLEAN:
×
246
                        sqlite3_bind_int64(stmt, lpc + 1, lv.lv_value.i);
×
247
                        retval[name] = fmt::to_string(lv.lv_value.i);
×
248
                        break;
×
249
                    case value_kind_t::VALUE_FLOAT:
×
250
                        sqlite3_bind_double(stmt, lpc + 1, lv.lv_value.d);
×
251
                        retval[name] = fmt::to_string(lv.lv_value.d);
×
252
                        break;
×
253
                    case value_kind_t::VALUE_INTEGER:
×
254
                        sqlite3_bind_int64(stmt, lpc + 1, lv.lv_value.i);
×
255
                        retval[name] = fmt::to_string(lv.lv_value.i);
×
256
                        break;
×
257
                    case value_kind_t::VALUE_NULL:
×
258
                        sqlite3_bind_null(stmt, lpc + 1);
×
259
                        retval[name] = string_fragment::from_c_str(
×
260
                            db_label_source::NULL_STR);
×
261
                        break;
×
262
                    default:
29✔
263
                        sqlite3_bind_text(stmt,
29✔
264
                                          lpc + 1,
265
                                          lv.text_value(),
266
                                          lv.text_length(),
29✔
267
                                          SQLITE_TRANSIENT);
268
                        retval[name] = lv.to_string();
87✔
269
                        break;
29✔
270
                }
271
            }
272
        } else {
29✔
273
            sqlite3_bind_null(stmt, lpc + 1);
×
274
            log_warning("Could not bind variable: %s", name);
×
275
            retval[name]
×
276
                = string_fragment::from_c_str(db_label_source::NULL_STR);
×
277
        }
278
    }
279

280
    return Ok(retval);
1,666✔
281
}
1,667✔
282

283
static void
284
execute_search(const std::string& search_cmd)
7✔
285
{
286
    textview_curses* tc = get_textview_for_mode(lnav_data.ld_mode);
7✔
287
    auto search_term = string_fragment(search_cmd)
7✔
288
                           .find_right_boundary(0, string_fragment::tag1{'\n'})
7✔
289
                           .to_string();
7✔
290
    tc->execute_search(search_term);
7✔
291
}
7✔
292

293
Result<std::string, lnav::console::user_message>
294
execute_sql(exec_context& ec, const std::string& sql, std::string& alt_msg)
1,682✔
295
{
296
    static auto op = lnav_operation{__FUNCTION__};
1,682✔
297

298
    auto op_guard = lnav_opid_guard::internal(op);
1,682✔
299
    auto_mem<sqlite3_stmt> stmt(sqlite3_finalize);
1,682✔
300
    timeval start_tv, end_tv;
301
    std::string stmt_str = trim(sql);
1,682✔
302
    std::string retval;
1,682✔
303
    int retcode = SQLITE_OK;
1,682✔
304

305
    if (lnav::sql::is_prql(stmt_str)) {
1,682✔
306
        log_info("compiling PRQL: %s", stmt_str.c_str());
42✔
307

308
#if HAVE_RUST_DEPS
309
        extern rust::Vec<lnav_rs_ext::SourceTreeElement> sqlite_extension_prql;
310
        auto opts = lnav_rs_ext::Options{true, "sql.sqlite", true};
42✔
311

312
        auto tree = sqlite_extension_prql;
42✔
313
        for (const auto& mod : lnav_prql_modules) {
126✔
314
            log_debug("lnav_rs_ext adding mod %s", mod.get_name());
84✔
315
            tree.emplace_back(lnav_rs_ext::SourceTreeElement{
168✔
316
                mod.get_name().data(),
84✔
317
                mod.to_string_fragment_producer()->to_string(),
168✔
318
            });
319
        }
320
        tree.emplace_back(lnav_rs_ext::SourceTreeElement{"", stmt_str});
42✔
321
        log_debug("BEGIN compiling tree");
42✔
322
        auto cr = lnav_rs_ext::compile_tree(tree, opts);
42✔
323
        log_debug("END compiling tree");
42✔
324

325
        for (const auto& msg : cr.messages) {
42✔
326
            if (msg.kind != lnav_rs_ext::MessageKind::Error) {
1✔
327
                continue;
×
328
            }
329

330
            auto stmt_al = attr_line_t(stmt_str);
1✔
331
            readline_sql_highlighter(stmt_al, lnav::sql::dialect::prql, 0);
1✔
332
            auto um
333
                = lnav::console::user_message::error(
×
334
                      attr_line_t("unable to compile PRQL: ").append(stmt_al))
2✔
335
                      .with_reason(
1✔
336
                          attr_line_t::from_ansi_str((std::string) msg.reason));
2✔
337
            if (!msg.display.empty()) {
1✔
338
                um.with_note(
1✔
339
                    attr_line_t::from_ansi_str((std::string) msg.display));
2✔
340
            }
341
            for (const auto& hint : msg.hints) {
1✔
342
                um.with_help(attr_line_t::from_ansi_str((std::string) hint));
×
343
                break;
×
344
            }
345
            return Err(um);
1✔
346
        }
1✔
347
        log_debug("done!");
41✔
348
        stmt_str = (std::string) cr.output;
41✔
349
#else
350
        auto um = lnav::console::user_message::error(
351
            attr_line_t("PRQL is not supported in this build"));
352
        return Err(um);
353
#endif
354
    }
44✔
355

356
    log_info("Executing SQL: %s", stmt_str.c_str());
1,681✔
357

358
    auto old_mode = lnav_data.ld_mode;
1,681✔
359
    lnav_data.ld_mode = ln_mode_t::BUSY;
1,681✔
360
    auto mode_fin = finally([old_mode]() { lnav_data.ld_mode = old_mode; });
1,681✔
361
    lnav_data.ld_bottom_source.grep_error("");
1,681✔
362
    lnav_data.ld_status[LNS_BOTTOM].set_needs_update();
1,681✔
363

364
    if (startswith(stmt_str, ".")) {
1,681✔
365
        std::vector<std::string> args;
7✔
366
        split_ws(stmt_str, args);
7✔
367

368
        const auto* sql_cmd_map
369
            = injector::get<readline_context::command_map_t*,
370
                            sql_cmd_map_tag>();
7✔
371
        auto cmd_iter = sql_cmd_map->find(args[0]);
7✔
372

373
        if (cmd_iter != sql_cmd_map->end()) {
7✔
374
            ec.ec_current_help = &cmd_iter->second->c_help;
7✔
375
            auto retval = cmd_iter->second->c_func(ec, stmt_str, args);
7✔
376
            ec.ec_current_help = nullptr;
7✔
377

378
            return retval;
7✔
379
        }
7✔
380
    }
7✔
381

382
    ec.ec_accumulator->clear();
1,674✔
383

384
    require(!ec.ec_source.empty());
1,674✔
385
    const auto& source = ec.ec_source.back();
1,674✔
386
    sql_progress_guard progress_guard(sql_progress,
387
                                      sql_progress_finished,
388
                                      source.s_location,
389
                                      source.s_content);
1,674✔
390
    gettimeofday(&start_tv, nullptr);
1,674✔
391

392
    const auto* curr_stmt = stmt_str.c_str();
1,674✔
393
    auto last_is_readonly = false;
1,674✔
394
    while (curr_stmt != nullptr) {
3,285✔
395
        const char* tail = nullptr;
3,285✔
396
        while (isspace(*curr_stmt)) {
3,285✔
397
            curr_stmt += 1;
×
398
        }
399
        retcode = sqlite3_prepare_v2(
3,285✔
400
            lnav_data.ld_db.in(), curr_stmt, -1, stmt.out(), &tail);
401
        if (retcode != SQLITE_OK) {
3,285✔
402
            const char* errmsg = sqlite3_errmsg(lnav_data.ld_db);
7✔
403

404
            alt_msg = "";
7✔
405

406
            auto um = lnav::console::user_message::error(
14✔
407
                          "failed to compile SQL statement")
408
                          .with_reason(errmsg)
14✔
409
                          .with_snippets(ec.ec_source)
14✔
410
                          .move();
7✔
411

412
            auto annotated_sql = annotate_sql_with_error(
413
                lnav_data.ld_db.in(), curr_stmt, tail);
7✔
414
            auto loc = um.um_snippets.back().s_location;
7✔
415
            if (curr_stmt == stmt_str.c_str()) {
7✔
416
                um.um_snippets.pop_back();
7✔
417
            } else {
418
                auto tail_iter = stmt_str.begin();
×
419

420
                std::advance(tail_iter, (curr_stmt - stmt_str.c_str()));
×
421
                loc.sl_line_number
×
422
                    += std::count(stmt_str.begin(), tail_iter, '\n');
×
423
            }
424

425
            um.with_snippet(lnav::console::snippet::from(loc, annotated_sql));
7✔
426

427
            return Err(um);
7✔
428
        }
7✔
429
        if (stmt == nullptr) {
3,278✔
430
            retcode = SQLITE_DONE;
1,611✔
431
            break;
1,611✔
432
        }
433
#ifdef HAVE_SQLITE3_STMT_READONLY
434
        last_is_readonly = sqlite3_stmt_readonly(stmt.in());
1,667✔
435
        if (ec.is_read_only() && !last_is_readonly) {
1,667✔
436
            return ec.make_error(
437
                "modifying statements are not allowed in this context: {}",
438
                sql);
×
439
        }
440
#endif
441
        bool done = false;
1,667✔
442

443
        auto bound_values = TRY(bind_sql_parameters(ec, stmt.in()));
1,667✔
444
        if (last_is_readonly) {
1,666✔
445
            ec.ec_sql_callback(ec, stmt.in());
1,532✔
446
        }
447
        while (!done) {
5,979✔
448
            retcode = sqlite3_step(stmt.in());
4,368✔
449

450
            switch (retcode) {
4,368✔
451
                case SQLITE_OK:
1,611✔
452
                case SQLITE_DONE: {
453
                    auto changes = sqlite3_changes(lnav_data.ld_db.in());
1,611✔
454

455
                    log_info("sqlite3_changes() -> %d", changes);
1,611✔
456
                    done = true;
1,611✔
457
                    break;
1,611✔
458
                }
459

460
                case SQLITE_ROW:
2,702✔
461
                    ec.ec_sql_callback(ec, stmt.in());
2,702✔
462
                    break;
2,702✔
463

464
                default: {
55✔
465
                    attr_line_t bound_note;
55✔
466

467
                    if (!bound_values.empty()) {
55✔
468
                        bound_note.append(
3✔
469
                            "the bound parameters are set as follows:\n");
470
                        for (const auto& bval : bound_values) {
11✔
471
                            auto val_as_str = fmt::to_string(bval.second);
8✔
472
                            auto sql_type = bval.second.match(
8✔
473
                                [](const std::string&) { return SQLITE_TEXT; },
5✔
474
                                [](const string_fragment&) {
×
475
                                    return SQLITE_TEXT;
×
476
                                },
477
                                [](bool) { return SQLITE_INTEGER; },
×
478
                                [](int64_t) { return SQLITE_INTEGER; },
1✔
479
                                [](null_value_t) { return SQLITE_NULL; },
1✔
480
                                [](double) { return SQLITE_FLOAT; });
1✔
481
                            auto scrubbed_val = scrub_ws(val_as_str.c_str());
8✔
482
                            truncate_to(scrubbed_val, 40);
8✔
483
                            bound_note.append("  ")
8✔
484
                                .append(lnav::roles::variable(bval.first))
16✔
485
                                .append(":")
8✔
486
                                .append(sqlite3_type_to_string(sql_type))
8✔
487
                                .append(" = ")
8✔
488
                                .append_quoted(scrubbed_val)
16✔
489
                                .append("\n");
8✔
490
                        }
8✔
491
                    }
492

493
                    log_error("sqlite3_step error code: %d", retcode);
55✔
494
                    auto um = sqlite3_error_to_user_message(lnav_data.ld_db)
110✔
495
                                  .with_note(bound_note)
55✔
496
                                  .move();
55✔
497

498
                    if (!ec.get_provenance<exec_context::keyboard_input>()) {
55✔
499
                        um.with_context_snippets(ec.ec_source)
110✔
500
                            .remove_internal_snippets();
55✔
501
                    }
502

503
                    return Err(um);
55✔
504
                }
55✔
505
            }
506
        }
507

508
        curr_stmt = tail;
1,611✔
509
    }
1,666✔
510

511
    if (last_is_readonly && !ec.ec_label_source_stack.empty()) {
1,611✔
512
        auto& dls = *ec.ec_label_source_stack.back();
1,507✔
513
        dls.dls_query_end = std::chrono::steady_clock::now();
1,507✔
514

515
        size_t memory_usage = 0, total_size = 0, cached_chunks = 0;
1,507✔
516
        for (auto cc = dls.dls_cell_container.cc_first.get(); cc != nullptr;
3,015✔
517
             cc = cc->cc_next.get())
1,508✔
518
        {
519
            total_size += cc->cc_capacity;
1,508✔
520
            if (cc->cc_data) {
1,508✔
521
                cached_chunks += 1;
1,507✔
522
                memory_usage += cc->cc_capacity;
1,507✔
523
            } else {
524
                memory_usage += cc->cc_compressed_size;
1✔
525
            }
526
        }
527
        log_debug(
1,507✔
528
            "cell memory footprint: total=%zu; actual=%zu; cached-chunks=%zu",
529
            total_size,
530
            memory_usage,
531
            cached_chunks);
532
    }
533
    gettimeofday(&end_tv, nullptr);
1,611✔
534
    lnav_data.ld_mode = old_mode;
1,611✔
535
    if (retcode == SQLITE_DONE) {
1,611✔
536
        if (lnav_data.ld_log_source.is_line_meta_changed()) {
1,611✔
537
            lnav_data.ld_log_source.text_filters_changed();
13✔
538
            lnav_data.ld_views[LNV_LOG].reload_data();
13✔
539
        }
540
        lnav_data.ld_filter_view.reload_data();
1,611✔
541
        lnav_data.ld_files_view.reload_data();
1,611✔
542

543
        lnav_data.ld_active_files.fc_files
544
            | lnav::itertools::for_each(&logfile::dump_stats);
1,611✔
545
        if (ec.ec_sql_callback != sql_callback) {
1,611✔
546
            retval = ec.ec_accumulator->get_string();
57✔
547
        } else {
548
            auto& dls = *(ec.ec_label_source_stack.back());
1,554✔
549
            if (!dls.dls_row_cursors.empty()) {
1,554✔
550
                lnav_data.ld_views[LNV_DB].reload_data();
1,440✔
551
                lnav_data.ld_views[LNV_DB].set_selection(0_vl);
1,440✔
552
                lnav_data.ld_views[LNV_DB].set_left(0);
1,440✔
553
                if (lnav_data.ld_flags & LNF_HEADLESS) {
1,440✔
554
                    if (ec.ec_local_vars.size() == 1) {
954✔
555
                        ensure_view(&lnav_data.ld_views[LNV_DB]);
864✔
556
                    }
557

558
                    retval = "";
954✔
559
                    alt_msg = "";
954✔
560
                } else if (dls.dls_row_cursors.size() == 1) {
486✔
561
                    retval = dls.get_row_as_string(0_vl);
438✔
562
                } else {
563
                    int row_count = dls.dls_row_cursors.size();
48✔
564
                    char row_count_buf[128];
565
                    timeval diff_tv;
566

567
                    timersub(&end_tv, &start_tv, &diff_tv);
48✔
568
                    snprintf(row_count_buf,
48✔
569
                             sizeof(row_count_buf),
570
                             ANSI_BOLD("%'d") " row%s matched in " ANSI_BOLD(
571
                                 "%ld.%03ld") " seconds",
572
                             row_count,
573
                             row_count == 1 ? "" : "s",
574
                             diff_tv.tv_sec,
575
                             std::max((long) diff_tv.tv_usec / 1000, 1L));
48✔
576
                    retval = row_count_buf;
48✔
577
                    if (dls.has_log_time_column()) {
48✔
578
                        alt_msg
579
                            = HELP_MSG_1(Q,
2✔
580
                                         "to switch back to the previous view "
581
                                         "at the matching 'log_time' value");
582
                    } else {
583
                        alt_msg = "";
46✔
584
                    }
585
                }
586
            }
587
#ifdef HAVE_SQLITE3_STMT_READONLY
588
            else if (last_is_readonly)
114✔
589
            {
590
                retval = "info: No rows matched";
25✔
591
                alt_msg = "";
25✔
592

593
                if (lnav_data.ld_flags & LNF_HEADLESS) {
25✔
594
                    if (ec.ec_local_vars.size() == 1) {
25✔
595
                        lnav_data.ld_views[LNV_DB].reload_data();
14✔
596
                        ensure_view(&lnav_data.ld_views[LNV_DB]);
14✔
597
                    }
598
                }
599
            }
600
#endif
601
        }
602
    }
603

604
    return Ok(retval);
1,611✔
605
}
1,682✔
606

607
Result<void, lnav::console::user_message>
608
multiline_executor::handle_command(const std::string& cmdline)
243✔
609
{
610
    this->me_last_result = TRY(execute_from_file(this->me_exec_context,
243✔
611
                                                 this->p_source,
612
                                                 this->p_starting_line_number,
613
                                                 cmdline));
614

615
    return Ok();
239✔
616
}
617

618
static Result<std::string, lnav::console::user_message>
619
execute_file_contents(exec_context& ec, const std::filesystem::path& path)
39✔
620
{
621
    static const std::filesystem::path stdin_path("-");
39✔
622
    static const std::filesystem::path dev_stdin_path("/dev/stdin");
39✔
623

624
    FILE* file;
625

626
    if (path == stdin_path || path == dev_stdin_path) {
39✔
627
        if (isatty(STDIN_FILENO)) {
3✔
628
            return ec.make_error("stdin has already been consumed");
×
629
        }
630
        file = stdin;
3✔
631
    } else if ((file = fopen(path.c_str(), "re")) == nullptr) {
36✔
632
        return ec.make_error("unable to open file");
×
633
    }
634

635
    std::string out_name;
39✔
636

637
    auto_mem<char> line;
39✔
638
    size_t line_max_size;
639
    ssize_t line_size;
640
    multiline_executor me(ec, path.string());
39✔
641

642
    ec.ec_local_vars.top()["0"] = path.string();
117✔
643
    ec.ec_path_stack.emplace_back(path.parent_path());
39✔
644
    exec_context::output_guard og(ec);
78✔
645
    while ((line_size = getline(line.out(), &line_max_size, file)) != -1) {
898✔
646
        TRY(me.push_back(string_fragment::from_bytes(line.in(), line_size)));
863✔
647
    }
648

649
    TRY(me.final());
35✔
650
    auto retval = std::move(me.me_last_result);
35✔
651

652
    if (file == stdin) {
35✔
653
        if (isatty(STDOUT_FILENO)) {
3✔
654
            log_perror(dup2(STDOUT_FILENO, STDIN_FILENO));
×
655
        }
656
    } else {
657
        fclose(file);
32✔
658
    }
659
    ec.ec_path_stack.pop_back();
35✔
660

661
    return Ok(retval);
35✔
662
}
39✔
663

664
Result<std::string, lnav::console::user_message>
665
execute_file(exec_context& ec, const std::string& path_and_args)
43✔
666
{
667
    static const intern_string_t SRC = intern_string::lookup("cmdline");
99✔
668
    static auto op = lnav_operation{__FUNCTION__};
43✔
669

670
    auto op_guard = lnav_opid_guard::internal(op);
43✔
671

672
    std::string retval, msg;
43✔
673
    shlex lexer(path_and_args);
43✔
674

675
    log_info("Executing file: %s", path_and_args.c_str());
43✔
676

677
    auto split_args_res = lexer.split(scoped_resolver{&ec.ec_local_vars.top()});
43✔
678
    if (split_args_res.isErr()) {
43✔
679
        auto split_err = split_args_res.unwrapErr();
×
680
        auto um = lnav::console::user_message::error(
×
681
                      "unable to parse script command-line")
682
                      .with_reason(split_err.se_error.te_msg)
×
683
                      .with_snippet(lnav::console::snippet::from(
×
684
                          SRC, lexer.to_attr_line(split_err.se_error)))
×
685
                      .move();
×
686

687
        return Err(um);
×
688
    }
689
    auto split_args = split_args_res.unwrap();
43✔
690
    if (split_args.empty()) {
43✔
691
        return ec.make_error("no script specified");
×
692
    }
693

694
    ec.ec_local_vars.emplace();
43✔
695

696
    auto script_name = split_args[0].se_value;
43✔
697
    auto& vars = ec.ec_local_vars.top();
43✔
698
    std::string star, open_error = "file not found";
86✔
699

700
    add_ansi_vars(vars);
43✔
701

702
    vars["#"] = fmt::to_string(split_args.size() - 1);
129✔
703
    for (size_t lpc = 0; lpc < split_args.size(); lpc++) {
129✔
704
        vars[fmt::to_string(lpc)] = split_args[lpc].se_value;
86✔
705
    }
706
    for (size_t lpc = 1; lpc < split_args.size(); lpc++) {
86✔
707
        if (lpc > 1) {
43✔
708
            star.append(" ");
21✔
709
        }
710
        star.append(split_args[lpc].se_value);
43✔
711
    }
712
    vars["__all__"] = star;
43✔
713

714
    std::vector<script_metadata> paths_to_exec;
43✔
715

716
    auto scripts = find_format_scripts(lnav_data.ld_config_paths);
43✔
717
    auto iter = scripts.as_scripts.find(script_name);
43✔
718
    if (iter != scripts.as_scripts.end()) {
43✔
719
        paths_to_exec = iter->second;
29✔
720
    }
721
    if (lnav::filesystem::is_url(script_name)) {
43✔
722
        auto_mem<CURLU> cu(curl_url_cleanup);
×
723
        cu = curl_url();
×
724
        auto set_rc = curl_url_set(cu, CURLUPART_URL, script_name.c_str(), 0);
×
725
        if (set_rc == CURLUE_OK) {
×
726
            auto_mem<char> scheme_part(curl_free);
×
727
            auto get_rc
728
                = curl_url_get(cu, CURLUPART_SCHEME, scheme_part.out(), 0);
×
729
            if (get_rc == CURLUE_OK
×
730
                && string_fragment::from_c_str(scheme_part.in()) == "file")
×
731
            {
732
                auto_mem<char> path_part;
×
733
                auto get_rc
734
                    = curl_url_get(cu, CURLUPART_PATH, path_part.out(), 0);
×
735
                if (get_rc == CURLUE_OK) {
×
736
                    auto rp_res = lnav::filesystem::realpath(path_part.in());
×
737
                    if (rp_res.isOk()) {
×
738
                        struct script_metadata meta;
×
739

740
                        meta.sm_path = rp_res.unwrap();
×
741
                        extract_metadata_from_file(meta);
×
742
                        paths_to_exec.push_back(meta);
×
743
                    }
744
                }
745
            }
746
        }
747
    }
748
    if (script_name == "-" || script_name == "/dev/stdin") {
43✔
749
        paths_to_exec.push_back({script_name, "", "", ""});
3✔
750
    } else if (access(script_name.c_str(), R_OK) == 0) {
40✔
751
        struct script_metadata meta;
7✔
752
        auto rp_res = lnav::filesystem::realpath(script_name);
7✔
753

754
        if (rp_res.isErr()) {
7✔
755
            log_error("unable to get realpath() of %s -- %s",
×
756
                      script_name.c_str(),
757
                      rp_res.unwrapErr().c_str());
758
            meta.sm_path = script_name;
×
759
        } else {
760
            meta.sm_path = rp_res.unwrap();
7✔
761
        }
762
        extract_metadata_from_file(meta);
7✔
763
        paths_to_exec.push_back(meta);
7✔
764
    } else if (errno != ENOENT) {
40✔
765
        open_error = lnav::from_errno().message();
×
766
    } else {
767
        auto script_path = std::filesystem::path(script_name);
33✔
768

769
        if (!script_path.is_absolute()) {
33✔
770
            script_path = ec.ec_path_stack.back() / script_path;
33✔
771
        }
772

773
        if (std::filesystem::is_regular_file(script_path)) {
33✔
774
            script_metadata meta;
×
775

776
            meta.sm_path = script_path;
×
777
            extract_metadata_from_file(meta);
×
778
            paths_to_exec.push_back(meta);
×
779
        } else if (errno != ENOENT) {
33✔
780
            open_error = lnav::from_errno().message();
×
781
        }
782
    }
33✔
783

784
    if (!paths_to_exec.empty()) {
43✔
785
        for (auto& path_iter : paths_to_exec) {
74✔
786
            if (!ec.ec_output_stack.empty()) {
39✔
787
                ec.ec_output_stack.back().od_format
39✔
788
                    = path_iter.sm_output_format;
39✔
789
                log_info("%s: setting out format for '%s' to %d",
39✔
790
                         script_name.c_str(),
791
                         ec.ec_output_stack.back().od_name.c_str(),
792
                         ec.ec_output_stack.back().od_format);
793
            }
794
            retval = TRY(execute_file_contents(ec, path_iter.sm_path));
39✔
795
        }
796
    }
797
    ec.ec_local_vars.pop();
39✔
798

799
    if (paths_to_exec.empty()) {
39✔
800
        return ec.make_error(
801
            "unknown script -- {} -- {}", script_name, open_error);
4✔
802
    }
803

804
    return Ok(retval);
35✔
805
}
58✔
806

807
Result<std::string, lnav::console::user_message>
808
execute_from_file(exec_context& ec,
243✔
809
                  const std::string& src,
810
                  int line_number,
811
                  const std::string& cmdline)
812
{
813
    std::string retval, alt_msg;
243✔
814
    auto _sg
815
        = ec.enter_source(intern_string::lookup(src), line_number, cmdline);
243✔
816

817
    lnav_data.ld_view_stack.top() | [&ec](auto* tc) {
243✔
818
        ec.ec_top_line = tc->get_selection().value_or(0_vl);
225✔
819
    };
225✔
820
    switch (cmdline[0]) {
243✔
821
        case ':':
104✔
822
            retval = TRY(execute_command(ec, cmdline.substr(1)));
104✔
823
            break;
104✔
824
        case '/':
1✔
825
            execute_search(cmdline.substr(1));
1✔
826
            break;
1✔
827
        case ';': {
136✔
828
            if (!ec.ec_msg_callback_stack.empty()) {
136✔
829
                auto src_slash = src.rfind('/');
132✔
830
                auto cmd_al
831
                    = attr_line_t(cmdline.substr(0, cmdline.find('\n')));
132✔
832
                readline_lnav_highlighter(cmd_al, std::nullopt);
132✔
833
                const auto um = lnav::console::user_message::info(
132✔
834
                                    attr_line_t("Executing command at ")
132✔
835
                                        .append(lnav::roles::file(
132✔
836
                                            src_slash != std::string::npos
837
                                                ? src.substr(src_slash + 1)
264✔
838
                                                : src))
839
                                        .append(":")
132✔
840
                                        .append(lnav::roles::number(
264✔
841
                                            fmt::to_string(line_number)))
264✔
842
                                        .append(" \u2014 ")
132✔
843
                                        .append(cmd_al))
132✔
844
                                    .move();
132✔
845
                ec.ec_msg_callback_stack.back()(um);
132✔
846
            }
132✔
847

848
            setup_logline_table(ec);
136✔
849
            retval = TRY(execute_sql(ec, cmdline.substr(1), alt_msg));
136✔
850
            break;
132✔
851
        }
852
        case '|':
2✔
853
            retval = TRY(execute_file(ec, cmdline.substr(1)));
2✔
854
            break;
2✔
855
        default:
×
856
            retval = TRY(execute_command(ec, cmdline));
×
857
            break;
×
858
    }
859

860
    log_info(
239✔
861
        "%s:%d:execute result -- %s", src.c_str(), line_number, retval.c_str());
862

863
    return Ok(retval);
239✔
864
}
243✔
865

866
Result<std::string, lnav::console::user_message>
867
execute_any(exec_context& ec, const std::string& cmdline_with_mode)
39✔
868
{
869
    if (cmdline_with_mode.empty()) {
39✔
870
        auto um = lnav::console::user_message::error("empty command")
×
871
                      .with_help(
×
872
                          "a command should start with ':', ';', '/', '|' and "
873
                          "followed by the operation to perform")
874
                      .move();
×
875
        if (!ec.ec_source.empty()) {
×
876
            um.with_snippet(ec.ec_source.back());
×
877
        }
878
        return Err(um);
×
879
    }
880

881
    std::string retval, alt_msg, cmdline = cmdline_with_mode.substr(1);
39✔
882
    auto _cleanup = finally([&ec] {
39✔
883
        if (ec.is_read_write() &&
44✔
884
            // only rebuild in a script or non-interactive mode so we don't
885
            // block the UI.
886
            lnav_data.ld_flags & LNF_HEADLESS)
5✔
887
        {
888
            rescan_files();
×
889
            wait_for_pipers(std::nullopt);
×
890
            rebuild_indexes_repeatedly();
×
891
        }
892
    });
78✔
893

894
    switch (cmdline_with_mode[0]) {
39✔
895
        case ':':
2✔
896
            retval = TRY(execute_command(ec, cmdline));
2✔
897
            break;
2✔
898
        case '/':
×
899
            execute_search(cmdline);
×
900
            break;
×
901
        case ';':
30✔
902
            setup_logline_table(ec);
30✔
903
            retval = TRY(execute_sql(ec, cmdline, alt_msg));
30✔
904
            break;
30✔
905
        case '|': {
7✔
906
            retval = TRY(execute_file(ec, cmdline));
7✔
907
            break;
7✔
908
        }
909
        default:
×
910
            retval = TRY(execute_command(ec, cmdline));
×
911
            break;
×
912
    }
913

914
    return Ok(retval);
39✔
915
}
39✔
916

917
void
918
execute_init_commands(
591✔
919
    exec_context& ec,
920
    std::vector<std::pair<Result<std::string, lnav::console::user_message>,
921
                          std::string>>& msgs)
922
{
923
    if (lnav_data.ld_cmd_init_done) {
591✔
924
        return;
×
925
    }
926

927
    std::string out_name;
591✔
928
    std::optional<exec_context::output_t> ec_out;
591✔
929
    auto_fd fd_copy;
591✔
930
    auto& dls = *(ec.ec_label_source_stack.back());
591✔
931
    int option_index = 1;
591✔
932

933
    {
934
        log_info("Executing initial commands");
591✔
935
        exec_context::output_guard og(ec, out_name, ec_out);
591✔
936

937
        for (auto& cmd : lnav_data.ld_commands) {
1,557✔
938
            static const auto COMMAND_OPTION_SRC
939
                = intern_string::lookup("command-option");
1,996✔
940

941
            std::string alt_msg;
966✔
942
            auto has_db_query = false;
966✔
943

944
            wait_for_children();
966✔
945

946
            lnav_data.ld_view_stack.top() | [&ec](auto* tc) {
966✔
947
                ec.ec_top_line = tc->get_selection().value_or(0_vl);
966✔
948
            };
966✔
949
            log_debug("init cmd: %s", cmd.c_str());
966✔
950
            {
951
                auto _sg
952
                    = ec.enter_source(COMMAND_OPTION_SRC, option_index++, cmd);
966✔
953
                switch (cmd.at(0)) {
966✔
954
                    case ':':
584✔
955
                        msgs.emplace_back(execute_command(ec, cmd.substr(1)),
584✔
956
                                          alt_msg);
957
                        break;
584✔
958
                    case '/':
6✔
959
                        execute_search(cmd.substr(1));
6✔
960
                        break;
6✔
961
                    case ';':
350✔
962
                        setup_logline_table(ec);
350✔
963
                        msgs.emplace_back(
350✔
964
                            execute_sql(ec, cmd.substr(1), alt_msg), alt_msg);
700✔
965
                        has_db_query = true;
350✔
966
                        break;
350✔
967
                    case '|':
26✔
968
                        msgs.emplace_back(execute_file(ec, cmd.substr(1)),
26✔
969
                                          alt_msg);
970
                        break;
26✔
971
                }
972

973
                rescan_files();
966✔
974
                auto deadline = ui_clock::now();
966✔
975
                if (lnav_data.ld_flags & LNF_HEADLESS) {
966✔
976
                    deadline += 5s;
966✔
977
                } else {
978
                    deadline += 500ms;
×
979
                }
980
                wait_for_pipers(deadline);
966✔
981
                rebuild_indexes_repeatedly();
966✔
982
            }
966✔
983
            if (has_db_query && !dls.dls_headers.empty()
350✔
984
                && lnav_data.ld_view_stack.size() == 1)
1,316✔
985
            {
986
                lnav_data.ld_views[LNV_DB].reload_data();
9✔
987
                ensure_view(LNV_DB);
9✔
988
            }
989
        }
966✔
990
    }
591✔
991
    lnav_data.ld_commands.clear();
591✔
992
    lnav_data.ld_cmd_init_done = true;
591✔
993
}
591✔
994

995
int
996
sql_callback(exec_context& ec, sqlite3_stmt* stmt)
4,131✔
997
{
998
    auto& dls = *(ec.ec_label_source_stack.back());
4,131✔
999
    const int ncols = sqlite3_column_count(stmt);
4,131✔
1000

1001
    if (!sqlite3_stmt_busy(stmt)) {
4,131✔
1002
        dls.clear();
1,482✔
1003

1004
        for (int lpc = 0; lpc < ncols; lpc++) {
4,502✔
1005
            const int type = sqlite3_column_type(stmt, lpc);
3,020✔
1006
            std::string colname = sqlite3_column_name(stmt, lpc);
3,020✔
1007

1008
            dls.push_header(colname, type);
3,020✔
1009
        }
3,020✔
1010
        return 0;
1,482✔
1011
    }
1012

1013
    int retval = 0;
2,649✔
1014
    auto set_vars = dls.dls_row_cursors.empty();
2,649✔
1015

1016
    if (dls.dls_row_cursors.empty()) {
2,649✔
1017
        dls.dls_query_start = std::chrono::steady_clock::now();
1,432✔
1018
        for (int lpc = 0; lpc < ncols; lpc++) {
4,269✔
1019
            int type = sqlite3_column_type(stmt, lpc);
2,837✔
1020
            std::string colname = sqlite3_column_name(stmt, lpc);
2,837✔
1021

1022
            bool graphable = (type == SQLITE_INTEGER || type == SQLITE_FLOAT);
2,837✔
1023
            auto& hm = dls.dls_headers[lpc];
2,837✔
1024
            hm.hm_column_type = type;
2,837✔
1025
            if (lnav_data.ld_db_key_names.count(colname) > 0) {
2,837✔
1026
                hm.hm_graphable = false;
555✔
1027
            } else if (graphable) {
2,282✔
1028
                dls.set_col_as_graphable(lpc);
650✔
1029
            }
1030
        }
2,837✔
1031
    }
1032

1033
    dls.dls_row_cursors.emplace_back(dls.dls_cell_container.end_cursor());
2,649✔
1034
    dls.dls_push_column = 0;
2,649✔
1035
    for (int lpc = 0; lpc < ncols; lpc++) {
11,832✔
1036
        const auto value_type = sqlite3_column_type(stmt, lpc);
9,183✔
1037
        db_label_source::column_value_t value;
9,183✔
1038
        auto& hm = dls.dls_headers[lpc];
9,183✔
1039

1040
        switch (value_type) {
9,183✔
1041
            case SQLITE_INTEGER:
2,673✔
1042
                value = (int64_t) sqlite3_column_int64(stmt, lpc);
2,673✔
1043
                hm.hm_align = text_align_t::end;
2,673✔
1044
                break;
2,673✔
1045
            case SQLITE_FLOAT:
231✔
1046
                value = sqlite3_column_double(stmt, lpc);
231✔
1047
                hm.hm_align = text_align_t::end;
231✔
1048
                break;
231✔
1049
            case SQLITE_NULL:
2,188✔
1050
                value = null_value_t{};
2,188✔
1051
                break;
2,188✔
1052
            default: {
4,091✔
1053
                auto frag = string_fragment::from_bytes(
4,091✔
1054
                    sqlite3_column_text(stmt, lpc),
1055
                    sqlite3_column_bytes(stmt, lpc));
4,091✔
1056
                if (!frag.empty()) {
4,091✔
1057
                    if (isdigit(frag[0])) {
4,024✔
1058
                        hm.hm_align = text_align_t::end;
1,385✔
1059
                        if (!hm.hm_graphable.has_value()) {
1,385✔
1060
                            auto split_res = humanize::try_from<double>(frag);
246✔
1061
                            if (split_res.has_value()) {
246✔
1062
                                dls.set_col_as_graphable(lpc);
59✔
1063
                            } else {
1064
                                hm.hm_graphable = false;
187✔
1065
                            }
1066
                        }
1067
                    } else if (!hm.hm_graphable.has_value()) {
2,639✔
1068
                        hm.hm_graphable = false;
1,037✔
1069
                    }
1070
                }
1071
                value = frag;
4,091✔
1072
                break;
4,091✔
1073
            }
1074
        }
1075
        dls.push_column(value);
9,183✔
1076
        if ((hm.hm_column_type == SQLITE_TEXT
9,183✔
1077
             || hm.hm_column_type == SQLITE_NULL)
4,990✔
1078
            && hm.hm_sub_type == 0)
6,314✔
1079
        {
1080
            switch (value_type) {
6,200✔
1081
                case SQLITE_TEXT:
3,979✔
1082
                    auto* raw_value = sqlite3_column_value(stmt, lpc);
3,979✔
1083
                    hm.hm_column_type = SQLITE_TEXT;
3,979✔
1084
                    hm.hm_sub_type = sqlite3_value_subtype(raw_value);
3,979✔
1085
                    break;
3,979✔
1086
            }
1087
        }
1088
        if (set_vars && !ec.ec_local_vars.empty() && !ec.ec_dry_run) {
9,183✔
1089
            if (sql_ident_needs_quote(hm.hm_name.c_str())) {
2,837✔
1090
                continue;
1,151✔
1091
            }
1092
            auto& vars = ec.ec_local_vars.top();
1,686✔
1093

1094
            vars[hm.hm_name] = value.match(
3,372✔
1095
                [](const string_fragment& sf) {
×
1096
                    return scoped_value_t{sf.to_string()};
742✔
1097
                },
1098
                [](int64_t i) { return scoped_value_t{i}; },
478✔
1099
                [](double d) { return scoped_value_t{d}; },
15✔
1100
                [](null_value_t) { return scoped_value_t{null_value_t{}}; });
3,823✔
1101
        }
1102
    }
9,183✔
1103

1104
    return retval;
2,649✔
1105
}
1106

1107
int
1108
internal_sql_callback(exec_context& ec, sqlite3_stmt* stmt)
32✔
1109
{
1110
    if (!sqlite3_stmt_busy(stmt)) {
32✔
1111
        return 0;
19✔
1112
    }
1113

1114
    const int ncols = sqlite3_column_count(stmt);
13✔
1115

1116
    auto& vars = ec.ec_local_vars.top();
13✔
1117

1118
    for (int lpc = 0; lpc < ncols; lpc++) {
33✔
1119
        const char* column_name = sqlite3_column_name(stmt, lpc);
20✔
1120

1121
        if (sql_ident_needs_quote(column_name)) {
20✔
1122
            continue;
×
1123
        }
1124

1125
        auto value_type = sqlite3_column_type(stmt, lpc);
20✔
1126
        scoped_value_t value;
20✔
1127
        switch (value_type) {
20✔
1128
            case SQLITE_INTEGER:
3✔
1129
                value = (int64_t) sqlite3_column_int64(stmt, lpc);
3✔
1130
                break;
3✔
1131
            case SQLITE_FLOAT:
×
1132
                value = sqlite3_column_double(stmt, lpc);
×
1133
                break;
×
1134
            case SQLITE_NULL:
3✔
1135
                value = null_value_t{};
3✔
1136
                break;
3✔
1137
            default:
14✔
1138
                value
1139
                    = std::string((const char*) sqlite3_column_text(stmt, lpc),
28✔
1140
                                  sqlite3_column_bytes(stmt, lpc));
28✔
1141
                break;
14✔
1142
        }
1143
        vars[column_name] = value;
20✔
1144
    }
20✔
1145

1146
    return 0;
13✔
1147
}
1148

1149
std::future<std::string>
1150
pipe_callback(exec_context& ec, const std::string& cmdline, auto_fd& fd)
7✔
1151
{
1152
    static auto& prompt = lnav::prompt::get();
7✔
1153
    auto out = ec.get_output();
7✔
1154

1155
    if (out) {
7✔
1156
        FILE* file = *out;
7✔
1157

1158
        return std::async(std::launch::async, [fd = std::move(fd), file]() {
14✔
1159
            char buffer[1024];
1160
            ssize_t rc;
1161

1162
            if (file == stdout) {
7✔
1163
                lnav_data.ld_stdout_used = true;
7✔
1164
            }
1165

1166
            while ((rc = read(fd, buffer, sizeof(buffer))) > 0) {
14✔
1167
                fwrite(buffer, rc, 1, file);
7✔
1168
            }
1169

1170
            return std::string();
14✔
1171
        });
7✔
1172
    }
1173
    std::error_code errc;
×
1174
    std::filesystem::create_directories(lnav::paths::workdir(), errc);
×
1175
    auto open_temp_res = lnav::filesystem::open_temp_file(lnav::paths::workdir()
×
1176
                                                          / "exec.XXXXXX");
×
1177
    if (open_temp_res.isErr()) {
×
1178
        return lnav::futures::make_ready_future(
1179
            fmt::format(FMT_STRING("error: cannot open temp file -- {}"),
×
1180
                        open_temp_res.unwrapErr()));
×
1181
    }
1182

1183
    auto tmp_pair = open_temp_res.unwrap();
×
1184

1185
    auto reader = std::thread(
1186
        [in_fd = std::move(fd), out_fd = std::move(tmp_pair.second)]() {
×
1187
            char buffer[1024];
1188
            ssize_t rc;
1189

1190
            while ((rc = read(in_fd, buffer, sizeof(buffer))) > 0) {
×
1191
                write(out_fd, buffer, rc);
×
1192
            }
1193
        });
×
1194
    reader.detach();
×
1195

1196
    static int exec_count = 0;
1197
    auto desc
1198
        = fmt::format(FMT_STRING("exec-{}-output {}"), exec_count++, cmdline);
×
1199
    lnav_data.ld_active_files.fc_file_names[tmp_pair.first]
×
1200
        .with_filename(desc)
×
1201
        .with_include_in_session(false)
×
1202
        .with_detect_format(false)
×
1203
        .with_init_location(0_vl);
×
1204
    lnav_data.ld_files_to_front.emplace_back(desc);
×
1205
    prompt.p_editor.set_alt_value(HELP_MSG_1(X, "to close the file"));
×
1206

1207
    return lnav::futures::make_ready_future(std::string());
×
1208
}
1209

1210
void
1211
add_global_vars(exec_context& ec)
661✔
1212
{
1213
    for (const auto& iter : lnav_config.lc_global_vars) {
10,582✔
1214
        shlex subber(iter.second);
9,921✔
1215
        std::string str;
9,921✔
1216

1217
        if (!subber.eval(str, scoped_resolver{&ec.ec_global_vars})) {
9,921✔
1218
            log_error("Unable to evaluate global variable value: %s",
×
1219
                      iter.second.c_str());
1220
            continue;
×
1221
        }
1222

1223
        ec.ec_global_vars[iter.first] = str;
9,921✔
1224
    }
9,921✔
1225
}
661✔
1226

1227
void
1228
exec_context::set_output(const std::string& name,
590✔
1229
                         FILE* file,
1230
                         int (*closer)(FILE*))
1231
{
1232
    log_info("redirecting command output to: %s", name.c_str());
590✔
1233
    this->ec_output_stack.back().od_output | [](auto out) {
590✔
1234
        if (out.second != nullptr) {
×
1235
            out.second(out.first);
×
1236
        }
1237
    };
1238
    this->ec_output_stack.back()
590✔
1239
        = output_desc{name, std::make_pair(file, closer)};
1,180✔
1240
}
590✔
1241

1242
void
1243
exec_context::clear_output()
76✔
1244
{
1245
    log_info("redirecting command output to screen");
76✔
1246
    this->ec_output_stack.back().od_output | [](auto out) {
76✔
1247
        if (out.second != nullptr) {
37✔
1248
            out.second(out.first);
37✔
1249
        }
1250
    };
37✔
1251
    this->ec_output_stack.back().od_name = "default";
76✔
1252
    this->ec_output_stack.back().od_output = std::nullopt;
76✔
1253
}
76✔
1254

1255
exec_context::exec_context(logline_value_vector* line_values,
3,499✔
1256
                           sql_callback_t sql_callback,
1257
                           pipe_callback_t pipe_callback)
3,499✔
1258
    : ec_line_values(line_values),
3,499✔
1259
      ec_accumulator(std::make_unique<attr_line_t>()),
3,499✔
1260
      ec_sql_callback(sql_callback), ec_pipe_callback(pipe_callback)
6,998✔
1261
{
1262
    this->ec_local_vars.push(std::map<std::string, scoped_value_t>());
3,499✔
1263
    this->ec_path_stack.emplace_back(".");
3,499✔
1264
    this->ec_output_stack.emplace_back("screen", std::nullopt);
3,499✔
1265
}
3,499✔
1266

1267
Result<std::string, lnav::console::user_message>
1268
exec_context::execute(source_location loc, const std::string& cmdline)
2✔
1269
{
1270
    static auto& prompt = lnav::prompt::get();
2✔
1271
    static const auto& dls = lnav_data.ld_db_row_source;
1272

1273
    lnav::textinput::history::op_guard hist_guard;
2✔
1274
    auto sg = this->enter_source(loc, cmdline);
2✔
1275

1276
    auto before_dls_gen = dls.dls_generation;
2✔
1277
    if (this->get_provenance<mouse_input>() && !prompt.p_editor.is_enabled()) {
2✔
1278
        auto& hist = prompt.get_history_for(cmdline[0]);
×
1279
        hist_guard = hist.start_operation(cmdline.substr(1));
×
1280
    }
1281

1282
    auto exec_res = execute_any(*this, cmdline);
2✔
1283
    if (exec_res.isErr()) {
2✔
1284
        hist_guard.og_status = log_level_t::LEVEL_ERROR;
×
1285
        if (!this->ec_msg_callback_stack.empty()) {
×
1286
            this->ec_msg_callback_stack.back()(exec_res.unwrapErr());
×
1287
        }
1288
    } else {
1289
        if (before_dls_gen != dls.dls_generation
4✔
1290
            && dls.dls_row_cursors.size() > 1)
2✔
1291
        {
1292
            ensure_view(LNV_DB);
×
1293
        }
1294
    }
1295

1296
    return exec_res;
4✔
1297
}
2✔
1298

1299
void
1300
exec_context::add_error_context(lnav::console::user_message& um)
74✔
1301
{
1302
    switch (um.um_level) {
74✔
1303
        case lnav::console::user_message::level::raw:
×
1304
        case lnav::console::user_message::level::info:
1305
        case lnav::console::user_message::level::ok:
1306
            return;
×
1307
        default:
74✔
1308
            break;
74✔
1309
    }
1310

1311
    if (!this->get_provenance<keyboard_input>() && um.um_snippets.empty()) {
74✔
1312
        um.with_snippets(this->ec_source);
34✔
1313
        um.remove_internal_snippets();
34✔
1314
    }
1315

1316
    if (this->ec_current_help != nullptr && um.um_help.empty()) {
74✔
1317
        attr_line_t help;
32✔
1318

1319
        format_help_text_for_term(*this->ec_current_help,
32✔
1320
                                  70,
1321
                                  help,
1322
                                  help_text_content::synopsis_and_summary);
1323
        um.with_help(help);
32✔
1324
    }
32✔
1325
}
1326

1327
exec_context::sql_callback_guard
1328
exec_context::push_callback(sql_callback_t cb)
5✔
1329
{
1330
    return sql_callback_guard(*this, cb);
5✔
1331
}
1332

1333
exec_context::source_guard
1334
exec_context::enter_source(source_location loc, const std::string& content)
2,438✔
1335
{
1336
    attr_line_t content_al{content};
2,438✔
1337
    content_al.with_attr_for_all(VC_ROLE.value(role_t::VCR_QUOTED_CODE));
2,438✔
1338
    readline_lnav_highlighter(content_al, -1);
2,438✔
1339
    this->ec_source.emplace_back(lnav::console::snippet::from(loc, content_al));
2,438✔
1340
    return {this};
4,876✔
1341
}
2,438✔
1342

1343
exec_context::output_guard::output_guard(exec_context& context,
665✔
1344
                                         std::string name,
1345
                                         const std::optional<output_t>& file,
1346
                                         text_format_t tf)
665✔
1347
    : sg_context(context), sg_active(!name.empty())
665✔
1348
{
1349
    if (name.empty()) {
665✔
1350
        return;
591✔
1351
    }
1352
    if (file) {
74✔
1353
        log_info("redirecting command output to: %s", name.c_str());
35✔
1354
    } else if (!context.ec_output_stack.empty()) {
39✔
1355
        tf = context.ec_output_stack.back().od_format;
39✔
1356
    }
1357
    context.ec_output_stack.emplace_back(std::move(name), file, tf);
74✔
1358
}
1359

1360
exec_context::output_guard::~output_guard()
665✔
1361
{
1362
    if (this->sg_active) {
665✔
1363
        this->sg_context.clear_output();
74✔
1364
        this->sg_context.ec_output_stack.pop_back();
74✔
1365
    }
1366
}
665✔
1367
exec_context::sql_callback_guard::sql_callback_guard(exec_context& context,
5✔
1368
                                                     sql_callback_t cb)
5✔
1369
    : scg_context(context), scg_old_callback(context.ec_sql_callback)
5✔
1370
{
1371
    context.ec_sql_callback = cb;
5✔
1372
}
5✔
1373
exec_context::sql_callback_guard::sql_callback_guard(sql_callback_guard&& other)
×
1374
    : scg_context(other.scg_context),
×
1375
      scg_old_callback(std::exchange(other.scg_old_callback, nullptr))
×
1376
{
1377
}
1378
exec_context::sql_callback_guard::~sql_callback_guard()
5✔
1379
{
1380
    if (this->scg_old_callback != nullptr) {
5✔
1381
        this->scg_context.ec_sql_callback = this->scg_old_callback;
5✔
1382
    }
1383
}
5✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc