// private slots: void REPL::startLoop() { char* userInput; // Load REPL history linenoiseHistoryLoad(m_historyFilepath.data()); //< requires "char *" while (m_looping && (userInput = linenoise(PROMPT)) != NULL) { if (userInput[0] != '\0') { // Send the user input to the main Phantom frame for evaluation m_webframe->evaluateJavaScript( QString(JS_EVAL_USER_INPUT).arg( QString(userInput).replace('"', "\\\""))); // Save command in the REPL history linenoiseHistoryAdd(userInput); linenoiseHistorySave(m_historyFilepath.data()); //< requires "char *" } free(userInput); } // If still "looping", close Phantom (usually caused by "CTRL+C" / "CTRL+D") if (m_looping) { m_parentPhantom->exit(); } }
void lineedit_stop() { if (l.buflen > 0) { linenoiseHistoryAdd(l.buf); /* Add to the history. */ linenoiseHistorySave("history.txt"); /* Save the history on disk. */ } }
void add_history (char *fname) { linenoiseHistoryAdd(fname); if (history_file_path) linenoiseHistorySave(history_file_path); }
// interactive line entry using linenoise static bool terminal(State& state, std::istream & in, std::ostream & out, Value& code) { std::string input; code = Value::Nil(); int status = 0; while(status == 0) { char* line = linenoise( input.size() == 0 ? "> " : "+ " ); if(line == 0) return true; input += line; if(line[0] != '\0') { linenoiseHistoryAdd(line); linenoiseHistorySave((char*)".riposte_history"); } free(line); input += "\n"; /* add the discarded newline back in */ if(input.size() > 0) { Parser parser(state); status = parser.execute(input.c_str(), input.size(), true, code); } } if (status == -1) code = Value::Nil(); return false; }
int srepl_init (sphia_t *sphia, cmd_t *cmds, opt_t *opts) { int rc = 0; char *line; linenoiseSetCompletionCallback(completion); linenoiseHistoryLoad("history.txt"); while((line = linenoise("sphia> ")) != NULL) { for(size_t i = 0; i < sizeof(*cmds) / sizeof(cmds[0]); i++) { if(0 == strcmp(cmds[i].name, line) || (NULL != cmds[i].alt && 0 == strcmp(cmds[i].alt, line))) { if(0 == strcmp(cmds[i].name, "set")) { parse_args(line, opts); } if(NULL != cmds[i].func) { if(0 == (rc = cmds[i].func(sphia, opts))) { linenoiseHistoryAdd(line); linenoiseHistorySave("History.txt"); }else { } } } } free(line); } return rc; }
static void repl() { int argc, j; char *line; sds *argv; config.interactive = 1; linenoiseSetCompletionCallback(completionCallback); while((line = linenoise(db ? "redislite> " : "not connected> ")) != NULL) { if (line[0] != '\0') { argv = sdssplitargs(line, &argc); linenoiseHistoryAdd(line); if (config.historyfile) { linenoiseHistorySave(config.historyfile); } if (argv == NULL) { printf("Invalid argument(s)\n"); continue; } else if (argc > 0) { if (strcasecmp(argv[0], "quit") == 0 || strcasecmp(argv[0], "exit") == 0) { exit(0); } else if (argc == 1 && !strcasecmp(argv[0], "clear")) { linenoiseClearScreen(); } else { long long start_time = mstime(), elapsed; if (cliSendCommand(argc, argv, 1) != REDISLITE_OK) { cliConnect(1); /* If we still cannot send the command, * print error and abort. */ if (cliSendCommand(argc, argv, 1) != REDISLITE_OK) { cliPrintContextErrorAndExit(); } } elapsed = mstime() - start_time; if (elapsed >= 500) { printf("(%.2fs)\n", (double)elapsed / 1000); } } } /* Free the argument vector */ for (j = 0; j < argc; j++) { sdsfree(argv[j]); } redislite_free(argv); } /* linenoise() returns malloc-ed lines like readline() */ free(line); } exit(0); }
static int readlines(void) { char *line; mpl_list_t *reqMsg = NULL; int quit = 0; mpl_list_t *tmp; completionStrings = calloc(maxStrings, sizeof(char *)); while((line = linenoise("PERS> ")) != NULL) { if (line[0] != '\0') { if (strcmp(line,"quit") && strncmp(line, "help ", 5)) { char *req; int ret = -1; req = formatCmdLine(line, "Req"); reqMsg = mpl_param_list_unpack_param_set(req, PERSONNEL_PARAM_SET_ID); if (!reqMsg) { printf("Protocol error\n"); ret = -1; } else if (checkCommand(reqMsg) == 0) { ret = pack_and_send(reqMsg); } mpl_param_list_destroy(&reqMsg); free(req); if (ret == 0) { fgets(buf, 1024, fi); printf("%s\n", buf); } } else if (!strncmp(line, "help ", 5)) { char *helptext; persfile_get_command_help(line, &helptext); if (helptext != NULL) { printf("%s", helptext); free(helptext); } else printf("No help\n"); } else { quit = 1; } linenoiseHistoryAdd(line); linenoiseHistorySave("history.txt"); /* Save every new entry */ free(line); while ((tmp = mpl_list_remove(&completionCallstack, NULL)) != NULL) { completion_callstack_entry_t *e; e = MPL_LIST_CONTAINER(tmp, completion_callstack_entry_t, list_entry); free(e); } } if (quit) break; } free(completionStrings); return 0; }
static int l_historysave(lua_State *L) { const char *filename = luaL_checkstring(L, 1); if(linenoiseHistorySave((char *) filename) < 0) { return handle_ln_error(L); } return handle_ln_ok(L); }
int main(int argc, char *argv[]) { int err; char *host = "127.0.0.1"; int port = 1276; char *prompt = "lamb"; /* Signal event processing */ lamb_signal_processing(); /* Start main event thread */ int sock; err = lamb_sock_connect(&sock, host, port); if (err) { fprintf(stderr, "Can't connect to %s server\n", host); return -1; } char *line; char *prgname = argv[0]; linenoiseSetCompletionCallback(completion); linenoiseSetHintsCallback(hints); linenoiseHistoryLoad(".lamb_history"); linenoiseHistorySetMaxLen(1000); while((line = linenoise("lamb> ")) != NULL) { /* Do something with the string. */ if (line[0] != '\0') { printf("echo: %s\n", line); linenoiseHistoryAdd(line); linenoiseHistorySave(".lamb_history"); } else if (line[0] != '\0' && !strncmp(line, "show client", 11)) { int id = atoi(line + 11); lamb_show_client(sock, id); linenoiseHistoryAdd(line); linenoiseHistorySave(".lamb_history"); } else if (line[0] != '\0') { printf("Unknown Command: '%s'\n", line); } free(line); } return 0; }
int main(int UNUSED(argc), char *argv[]) { // int i; const int num_threads = 2; pthread_t tid[num_threads]; // void *status; struct listen_param lis_para; struct send_param send_para; char *line; //mtrace(); que_msg = CreateQueue(100); sem_init(&sem_msg, 0, 0); memset(&dev_map, 0, sizeof(dev_map)); lis_para.port = SERVER_PORT; lis_para.receive_thread = receive_thread; pthread_create(&tid[0], NULL, listen_thread, &lis_para); send_para.que_msg = que_msg; send_para.mutex_msg = &mutex_msg; send_para.sem_msg = &sem_msg; pthread_create(&tid[1], NULL, send_thread, &send_para); linenoiseHistoryLoad("hist-srv.txt"); /* Load the history at startup */ while((line = linenoise("srv> ")) != NULL) { /* Do something with the string. */ if (line[0] != '\0' && line[0] != '/') { //printf("echo: '%s'\n", line); linenoiseHistoryAdd(line); /* Add to the history. */ linenoiseHistorySave("hist-srv.txt"); /* Save the history on disk. */ cmd_handle(0, line); } else if (!strncmp(line,"/q",2)) { free(line); break; } else if (!strncmp(line,"/historylen",11)) { /* The "/historylen" command will change the history len. */ int len = atoi(line+11); linenoiseHistorySetMaxLen(len); } else if (line[0] == '/') { printf("Unreconized command: %s\n", line); } else { printf("\n"); } free(line); } // for (i = 0; i < num_threads; i++) // pthread_join(tid[i],&status); return 0; }
int main(int argc, char *argv[]) { char *line; #ifdef HAVE_MULTILINE /* Note: multiline support has not yet been integrated */ char *prgname = argv[0]; /* Parse options, with --multiline we enable multi line editing. */ while(argc > 1) { argc--; argv++; if (!strcmp(*argv,"--multiline")) { linenoiseSetMultiLine(1); printf("Multi-line mode enabled.\n"); } else { fprintf(stderr, "Usage: %s [--multiline]\n", prgname); exit(1); } } #endif #ifndef NO_COMPLETION /* Set the completion callback. This will be called every time the * user uses the <tab> key. */ linenoiseSetCompletionCallback(completion); #endif /* Load history from file. The history file is just a plain text file * where entries are separated by newlines. */ linenoiseHistoryLoad("history.txt"); /* Load the history at startup */ /* Now this is the main loop of the typical linenoise-based application. * The call to linenoise() will block as long as the user types something * and presses enter. * * The typed string is returned as a malloc() allocated string by * linenoise, so the user needs to free() it. */ while((line = linenoise("hello> ")) != NULL) { /* Do something with the string. */ if (line[0] != '\0' && line[0] != '/') { printf("echo: '%s'\n", line); linenoiseHistoryAdd(line); /* Add to the history. */ linenoiseHistorySave("history.txt"); /* Save the history on disk. */ } else if (!strncmp(line,"/historylen",11)) { /* The "/historylen" command will change the history len. */ int len = atoi(line+11); linenoiseHistorySetMaxLen(len); } else if (line[0] == '/') { printf("Unreconized command: %s\n", line); } free(line); } return 0; }
int main(void) { setlocale(LC_ALL, ""); signal(SIGINT, sig); signal(SIGQUIT, sig); signal(SIGHUP, sig); signal(SIGTERM, sig); linenoiseSetCompletionCallback(completion); char *home_dir = getenv("HOME"); assert(home_dir != NULL); char *histfile_path = get_hist_path(home_dir); if (NULL == histfile_path) { fprintf(stderr,"cannot determine history file path\n"); exit(EXIT_FAILURE); } printf("history file: %s\n",histfile_path); linenoiseHistoryLoad(histfile_path); char *line; cmd_request *cr; while((line = linenoise("qind> ")) != NULL) { if (strncmp(line,"",MAX_CMD_LEN) == 0) { continue; } cr = new_cmd_request(line); if (NULL == cr) { fprintf(stderr,"could not make cmd_request\n"); exit(EXIT_FAILURE); } dump_cmd_request(cr); if (strncmp(QUIT_CMD,line,MAX_CMD_LEN) == 0) { printf("<quitting>\n"); break; } linenoiseHistoryAdd(cr->request); destroy_cmd_request(cr); free(line); } linenoiseHistorySave(histfile_path); free(histfile_path); exit(EXIT_SUCCESS); }
int main(int argc, char *argv[]) { char *line; linenoiseSetCompletionCallback(completion); linenoiseHistoryLoad("history.txt"); /* Load the history at startup */ while((line = linenoise("hello> ")) != NULL) { if (line[0] != '\0') { printf("echo: '%s'\n", line); linenoiseHistoryAdd(line); linenoiseHistorySave("history.txt"); /* Save every new entry */ } free(line); } return 0; }
static void repl() { int argc, j; char *line; sds *argv; config.interactive = 1; while((line = linenoise("redis> ")) != NULL) { if (line[0] != '\0') { argv = sdssplitargs(line,&argc); linenoiseHistoryAdd(line); if (config.historyfile) linenoiseHistorySave(config.historyfile); if (argv == NULL) { printf("Invalid argument(s)\n"); continue; } else if (argc > 0) { if (strcasecmp(argv[0],"quit") == 0 || strcasecmp(argv[0],"exit") == 0) { exit(0); } else { int err; if ((err = cliSendCommand(argc, argv, 1)) != 0) { if (err == ECONNRESET) { printf("Reconnecting... "); fflush(stdout); if (cliConnect(1) == -1) exit(1); printf("OK\n"); cliSendCommand(argc,argv,1); } } } } /* Free the argument vector */ for (j = 0; j < argc; j++) sdsfree(argv[j]); zfree(argv); } /* linenoise() returns malloc-ed lines like readline() */ free(line); } exit(0); }
int main(int argc, char **argv) { char* line; unsigned int promptNb = 1; char promptMsg[100]; srand(time(NULL)); printLogo(); /* Set the completion callback. This will be called every time the * user uses the <tab> key. */ linenoiseSetCompletionCallback(completion); /* Load history from file.*/ linenoiseHistoryLoad(HIST_FILENAME); /* Load the history at startup */ snprintf(promptMsg, 100, "%s[%d]: ", "\033[0m", promptNb); while((line = linenoise(promptMsg)) != NULL) { linenoiseHistoryAdd(line); /* Add to the history. */ linenoiseHistorySave(HIST_FILENAME); /* Save the history on disk. */ /* Do something with the string. */ rmSuperscript(line); if(line[0] == '/') parseCommand(&(line[1])); else if(!strcmp(line, "exit") || !strcmp(line, "quit") || (line[1] == 0 && (line[0] == 'e' || line[0] == 'q'))) break; else if(line[0] != '\0') { simpleParserAPI(line); } snprintf(promptMsg, 100, "[%d]: ", ++promptNb); } finalProcessing(); return 0; }
/* Main function. */ int main(int argc, char *argv[]) { cli_t cli; char *hostname = DEFAULT_HOST; char history_file[4096]; ybool_t interactive_mode = YTRUE; bzero(&cli, sizeof(cli_t)); cli.autocheck = YTRUE; if (argc == 2 && argv[1][0] != '-') hostname = argv[1]; if (argc == 3 && !strcmp(argv[2], "-")) interactive_mode = YFALSE; // init database connection if ((cli.finedb = finedb_create(hostname, 11138)) == NULL) { printf_color("red", "Memory error."); printf("\n"); exit(1); } if (finedb_connect(cli.finedb) != FINEDB_OK) { printf_color("red", "Unable to connect to server '%s' on port '%d'.", argv[1], 11138); printf("\n"); exit(2); } // interactive mode init if (interactive_mode) { char *home = NULL; if ((home = getenv("HOME")) != NULL) { FILE *hist; snprintf(history_file, sizeof(history_file), "%s/%s", home, HISTORY_FILE); if ((hist = fopen(history_file, "w+")) != NULL) { fclose(hist); linenoiseHistoryLoad(HISTORY_FILE); } linenoiseSetCompletionCallback(cli_completion); } } // main loop for (; ; ) { char buff[4096], *line = NULL, *pt, *cmd; if (!interactive_mode) { ssize_t bufsz, linesz = 0; while ((bufsz = read(0, buff, sizeof(buff))) > 0) { pt = (char*)malloc(linesz + bufsz + 1); memcpy(pt, line, linesz); memcpy((void*)((size_t)pt + linesz), buff, bufsz); linesz += bufsz; pt[linesz] = '\0'; if (line) free(line); line = pt; } } else { snprintf(buff, sizeof(buff), "%s > ", (cli.dbname ? cli.dbname : "default")); if ((line = linenoise(buff)) == NULL) break; } pt = line; LTRIM(pt); cmd = pt; // add command line to history linenoiseHistoryAdd(cmd); linenoiseHistorySave(history_file); // extract the command while (*pt && !IS_SPACE(*pt)) ++pt; *pt++ = '\0'; LTRIM(pt); /* command management */ if (cmd[0] == '\0') goto reloop; //continue; // local commands, no need for a running connection if (!strcasecmp(cmd, "exit") || !strcasecmp(cmd, "quit")) exit(0); if (!strcasecmp(cmd, "help") || cmd[0] == '?') { command_help(); goto reloop; //continue; } else if (!strcasecmp(cmd, "sync")) { command_sync(&cli); goto reloop; //continue; } else if (!strcasecmp(cmd, "async")) { command_async(&cli); goto reloop; //continue; } // commands that need a running connection if (!strcasecmp(cmd, "use")) command_use(&cli, pt); else if (!strcasecmp(cmd, "get")) command_get(&cli, pt); else if (!strcasecmp(cmd, "del")) command_del(&cli, pt); else if (!strcasecmp(cmd, "put")) command_send_data(&cli, pt, YFALSE, YFALSE); else if (!strcasecmp(cmd, "add")) command_send_data(&cli, pt, YTRUE, YFALSE); else if (!strcasecmp(cmd, "update")) command_send_data(&cli, pt, YFALSE, YTRUE); else if (!strcasecmp(cmd, "inc")) command_inc(&cli, pt); else if (!strcasecmp(cmd, "dec")) command_dec(&cli, pt); else if (!strcasecmp(cmd, "start")) command_start(&cli); else if (!strcasecmp(cmd, "stop")) command_stop(&cli); #if 0 else if (!strcasecmp(cmd, "list")) command_list(&cli, pt); #endif else if (!strcasecmp(cmd, "ping")) command_ping(&cli); else if (!strcasecmp(cmd, "autocheck")) command_autocheck(&cli, pt); else { printf_color("red", "Bad command."); printf("\n"); } reloop: free(line); } return (0); }
int main(int argc, char **argv) { char *address_parser_dir = LIBPOSTAL_ADDRESS_PARSER_DIR; char *history_file = "address_parser.history"; if (argc > 1) { address_parser_dir = argv[1]; } printf("Loading models...\n"); if (!libpostal_setup() || !libpostal_setup_parser()) { exit(EXIT_FAILURE); } printf("\n"); printf("Welcome to libpostal's address parser.\n\n"); printf("Type in any address to parse and print the result.\n\n"); printf("Special commands:\n\n"); printf(".language [code] to specify a language\n"); printf(".country [code] to specify a country\n"); printf(".exit to quit the program\n\n"); char *language = NULL; char *country = NULL; char *input = NULL; while((input = linenoise("> ")) != NULL) { if (input[0] != '\0') { linenoiseHistoryAdd(input); /* Add to the history. */ linenoiseHistorySave(history_file); /* Save the history on disk. */ } if (strcmp(input, ".exit") == 0) { printf("Fin!\n"); free(input); break; } else if (strncmp(input, ".language", 9) == 0) { size_t num_tokens = 0; cstring_array *command = cstring_array_split(input, " ", 1, &num_tokens); if (num_tokens > 1) { if (language != NULL) { free(language); } language = strdup(cstring_array_get_string(command, 1)); } else { printf("Must specify language code\n"); } cstring_array_destroy(command); goto next_input; } else if (strncmp(input, ".country", 8) == 0) { size_t num_tokens = 0; cstring_array *command = cstring_array_split(input, " ", 1, &num_tokens); if (cstring_array_num_strings(command) > 1) { if (country != NULL) { free(country); } country = strdup(cstring_array_get_string(command, 1)); } else { printf("Must specify country code\n"); } cstring_array_destroy(command); goto next_input; } else if (strlen(input) == 0) { goto next_input; } address_parser_response_t *parsed; address_parser_options_t options = get_libpostal_address_parser_default_options(); if ((parsed = parse_address(input, options))) { printf("\n"); printf("Result:\n\n"); printf("{\n"); for (int i = 0; i < parsed->num_components; i++) { char *json_string = json_encode_string(parsed->components[i]); printf(" \"%s\": %s%s\n", parsed->labels[i], json_string, i < parsed->num_components - 1 ? "," : ""); } printf("}\n"); printf("\n"); address_parser_response_destroy(parsed); } else { printf("Error parsing address\n"); } next_input: free(input); } libpostal_teardown(); libpostal_teardown_parser(); }
int main(int argc, char *argv[]) { printf("%s", banner); char line[8000]; char k[8000]; int i, h, vlen, offt, len; if (argc < 3) { puts("Usage: run [foo.idx] [foo.sql]"); exit(-1); } CFP = fopen(argv[1], "r"); for (i=0; i < BUCKETS; i++) { HT[i].n = NULL; HT[i].len = 0; } int c = 0; while ((len=fgetln(line)) != -1) { parse(line, k, &vlen, &offt); //printf("%s:%d@%d\n", k, vlen, offt); htput(k, vlen, offt); c++; } printf("Loaded \t%d words\n", c); int fd = open(argv[2], O_RDONLY); struct stat sb; fstat(fd, &sb); int sz; sz = sb.st_size; void *ad; ad = mmap(NULL, sz, PROT_READ, MAP_PRIVATE, fd, 0); #define HISTORY_FILE ".lookups" linenoiseHistoryLoad(HISTORY_FILE); /* Load the history at startup */ linenoiseSetCompletionCallback(completion); char *str; while((str = linenoise(">>> ")) != NULL) { if (strcmp(str, "/exit") == 0) break; if (str[0] != '\0') { len = strlen(str); if (len < 1) continue; h = hash(str); if (HT[h].len) { NODE *n = lookup(str, HT[h].n); if (n) { int offt, vlen; offt = n->idx->offt; vlen = n->idx->vlen; char *p = ad + offt; while (--vlen) printf("%c", *p++); } else { puts("Not found in tree"); int j; for (j=0,i=0; i < cc_len; i++) { if (complet(str, CC[i].key) == 0) { printf("%d) %s\n", ++j, CC[i].key); } } //TODO also do levenshtein search if no found } } else puts("Not found in table"); linenoiseHistoryAdd(str); linenoiseHistorySave(HISTORY_FILE); /* Save every new entry */ printf("\n"); } if (str) free(str); } printf("\n"); if (str) free(str); close(fd); for (i=0; i < BUCKETS; i++) { if (HT[i].len) { //printf("bucket %d: %d keys\n", i, HT[i].len); freetree(HT[i].n); } } for (i=0; i < cc_len; i++) { free(CC[i].key); } return 0; }
static void repl() { sds historyfile = NULL; int history = 0; char *line; int argc; sds *argv; config.interactive = 1; linenoiseSetCompletionCallback(completionCallback); /* Only use history when stdin is a tty. */ if (isatty(fileno(stdin))) { history = 1; if (getenv("HOME") != NULL) { historyfile = sdscatprintf(sdsempty(),"%s/.rediscli_history",getenv("HOME")); linenoiseHistoryLoad(historyfile); } } cliRefreshPrompt(); while((line = linenoise(context ? config.prompt : "not connected> ")) != NULL) { if (line[0] != '\0') { argv = sdssplitargs(line,&argc); if (history) linenoiseHistoryAdd(line); if (historyfile) linenoiseHistorySave(historyfile); if (argv == NULL) { printf("Invalid argument(s)\n"); free(line); continue; } else if (argc > 0) { if (strcasecmp(argv[0],"quit") == 0 || strcasecmp(argv[0],"exit") == 0) { exit(0); } else if (argc == 3 && !strcasecmp(argv[0],"connect")) { sdsfree(config.hostip); config.hostip = sdsnew(argv[1]); config.hostport = atoi(argv[2]); cliConnect(1); } else if (argc == 1 && !strcasecmp(argv[0],"clear")) { linenoiseClearScreen(); } else { long long start_time = mstime(), elapsed; int repeat, skipargs = 0; repeat = atoi(argv[0]); if (argc > 1 && repeat) { skipargs = 1; } else { repeat = 1; } while (1) { config.cluster_reissue_command = 0; if (cliSendCommand(argc-skipargs,argv+skipargs,repeat) != REDIS_OK) { cliConnect(1); /* If we still cannot send the command print error. * We'll try to reconnect the next time. */ if (cliSendCommand(argc-skipargs,argv+skipargs,repeat) != REDIS_OK) cliPrintContextError(); } /* Issue the command again if we got redirected in cluster mode */ if (config.cluster_mode && config.cluster_reissue_command) { cliConnect(1); } else { break; } } elapsed = mstime()-start_time; if (elapsed >= 500) { printf("(%.2fs)\n",(double)elapsed/1000); } } } /* Free the argument vector */ while(argc--) sdsfree(argv[argc]); zfree(argv); } /* linenoise() returns malloc-ed lines like readline() */ free(line); } exit(0); }
void Jim_HistorySave(const char *filename) { #ifdef USE_LINENOISE linenoiseHistorySave(filename); #endif }
bool Console::saveHistory(const std::string& fileName) { return linenoiseHistorySave(fileName.c_str()) == 0; }
void run_console() { initialize_console(); /* Register commands */ esp_console_register_help_command(); const esp_console_cmd_t cmd1 = { .command = "motortest", .help = "Test the motors", .hint = NULL, .func = &motor_test, .argtable = nullptr }; ESP_ERROR_CHECK(esp_console_cmd_register(&cmd1)); const esp_console_cmd_t cmd2 = { .command = "i2cscan", .help = "Scan for I2C devices", .hint = NULL, .func = &i2c_scan, .argtable = nullptr }; ESP_ERROR_CHECK(esp_console_cmd_register(&cmd2)); /* Prompt to be printed before each line. * This can be customized, made dynamic, etc. */ const char* prompt = LOG_COLOR_I "esp32> " LOG_RESET_COLOR; printf("\n" "This is an example of ESP-IDF console component.\n" "Type 'help' to get the list of commands.\n" "Use UP/DOWN arrows to navigate through command history.\n" "Press TAB when typing command name to auto-complete.\n"); /* Figure out if the terminal supports escape sequences */ int probe_status = linenoiseProbe(); if (probe_status) { /* zero indicates success */ printf("\n" "Your terminal application does not support escape sequences.\n" "Line editing and history features are disabled.\n" "On Windows, try using Putty instead.\n"); linenoiseSetDumbMode(1); #if CONFIG_LOG_COLORS /* Since the terminal doesn't support escape sequences, * don't use color codes in the prompt. */ prompt = "esp32> "; #endif //CONFIG_LOG_COLORS } /* Main loop */ while(true) { /* Get a line using linenoise. * The line is returned when ENTER is pressed. */ char* line = linenoise(prompt); if (line == NULL) { /* Ignore empty lines */ continue; } /* Add the command to the history */ linenoiseHistoryAdd(line); #if CONFIG_STORE_HISTORY /* Save command history to filesystem */ linenoiseHistorySave(HISTORY_PATH); #endif /* Try to run the command */ int ret; esp_err_t err = esp_console_run(line, &ret); if (err == ESP_ERR_NOT_FOUND) { printf("Unrecognized command\n"); } else if (err == ESP_ERR_INVALID_ARG) { // command was empty } else if (err == ESP_OK && ret != ESP_OK) { printf("Command returned non-zero error code: 0x%x (%s)\n", ret, esp_err_to_name(err)); } else if (err != ESP_OK) { printf("Internal error: %s\n", esp_err_to_name(err)); } /* linenoise allocates line buffer on the heap, so need to free it */ linenoiseFree(line); } }
int write_history(const char *filename) { return -1 != linenoiseHistorySave(filename != NULL ? (char *)filename : DEFAULT_HISTORY_FILE) ? 0 : errno; }
int main(int argc, char **argv) { struct option long_options[] = { {"help", no_argument, NULL, 'h'}, {"legal", no_argument, NULL, 'l'}, {"verbose", no_argument, NULL, 'v'}, {"quiet", no_argument, NULL, 'q'}, {"repl", no_argument, NULL, 'r'}, {"static-fns", no_argument, NULL, 's'}, {"elide-asserts", no_argument, NULL, 'a'}, {"cache", required_argument, NULL, 'k'}, {"eval", required_argument, NULL, 'e'}, {"theme", required_argument, NULL, 't'}, {"classpath", required_argument, NULL, 'c'}, {"auto-cache", no_argument, NULL, 'K'}, {"init", required_argument, NULL, 'i'}, {"main", required_argument, NULL, 'm'}, // development options {"javascript", no_argument, NULL, 'j'}, {"out", required_argument, NULL, 'o'}, {0, 0, 0, 0} }; int opt, option_index; while ((opt = getopt_long(argc, argv, "h?lvrsak:je:t:c:o:Ki:qm:", long_options, &option_index)) != -1) { switch (opt) { case 'h': usage(argv[0]); exit(0); case 'l': legal(); return 0; case 'v': verbose = true; break; case 'q': quiet = true; break; case 'r': repl = true; break; case 's': static_fns = true; break; case 'a': elide_asserts = true; break; case 'k': cache_path = argv[optind - 1]; break; case 'K': cache_path = ".planck_cache"; { char *path_copy = strdup(cache_path); char *dir = dirname(path_copy); if (mkdir_p(dir) < 0) { fprintf(stderr, "Could not create %s: %s\n", cache_path, strerror(errno)); } free(path_copy); } break; case 'j': javascript = true; break; case 'e': num_scripts += 1; scripts = realloc(scripts, num_scripts * sizeof(struct script)); scripts[num_scripts - 1].type = "text"; scripts[num_scripts - 1].expression = true; scripts[num_scripts - 1].source = argv[optind - 1]; break; case 'i': num_scripts += 1; scripts = realloc(scripts, num_scripts * sizeof(struct script)); scripts[num_scripts - 1].type = "path"; scripts[num_scripts - 1].expression = false; scripts[num_scripts - 1].source = argv[optind - 1]; break; case 'm': main_ns_name = argv[optind - 1]; case 't': theme = argv[optind - 1]; break; case 'c': { char *classpath = argv[optind - 1]; char *source = strtok(classpath, ":"); while (source != NULL) { char *type = "src"; if (str_has_suffix(source, ".jar") == 0) { type = "jar"; } num_src_paths += 1; src_paths = realloc(src_paths, num_src_paths * sizeof(struct src_path)); src_paths[num_src_paths - 1].type = type; src_paths[num_src_paths - 1].path = strdup(source); source = strtok(NULL, ":"); } break; } case 'o': out_path = argv[optind - 1]; break; case '?': usage(argv[0]); exit(1); default: printf("unhandled argument: %c\n", opt); } } int num_rest_args = 0; char **rest_args = NULL; if (optind < argc) { num_rest_args = argc - optind; rest_args = malloc((argc - optind) * sizeof(char*)); int i = 0; while (optind < argc) { rest_args[i++] = argv[optind++]; } } if (num_scripts == 0 && main_ns_name == NULL && num_rest_args == 0) { repl = true; } if (main_ns_name != NULL && repl) { printf("Only one main-opt can be specified."); } JSGlobalContextRef ctx = JSGlobalContextCreate(NULL); JSStringRef nameRef = JSStringCreateWithUTF8CString("planck"); JSGlobalContextSetName(ctx, nameRef); evaluate_script(ctx, "var global = this;", "<init>"); register_global_function(ctx, "AMBLY_IMPORT_SCRIPT", function_import_script); bootstrap(ctx, out_path); register_global_function(ctx, "PLANCK_CONSOLE_LOG", function_console_log); register_global_function(ctx, "PLANCK_CONSOLE_ERROR", function_console_error); evaluate_script(ctx, "var console = {};"\ "console.log = PLANCK_CONSOLE_LOG;"\ "console.error = PLANCK_CONSOLE_ERROR;", "<init>"); evaluate_script(ctx, "var PLANCK_VERSION = \"" PLANCK_VERSION "\";", "<init>"); // require app namespaces evaluate_script(ctx, "goog.require('planck.repl');", "<init>"); // without this things won't work evaluate_script(ctx, "var window = global;", "<init>"); register_global_function(ctx, "PLANCK_READ_FILE", function_read_file); register_global_function(ctx, "PLANCK_LOAD", function_load); register_global_function(ctx, "PLANCK_LOAD_DEPS_CLJS_FILES", function_load_deps_cljs_files); register_global_function(ctx, "PLANCK_CACHE", function_cache); register_global_function(ctx, "PLANCK_EVAL", function_eval); register_global_function(ctx, "PLANCK_GET_TERM_SIZE", function_get_term_size); register_global_function(ctx, "PLANCK_PRINT_FN", function_print_fn); register_global_function(ctx, "PLANCK_PRINT_ERR_FN", function_print_err_fn); register_global_function(ctx, "PLANCK_SET_EXIT_VALUE", function_set_exit_value); is_tty = isatty(STDIN_FILENO) == 1; register_global_function(ctx, "PLANCK_RAW_READ_STDIN", function_raw_read_stdin); register_global_function(ctx, "PLANCK_RAW_WRITE_STDOUT", function_raw_write_stdout); register_global_function(ctx, "PLANCK_RAW_FLUSH_STDOUT", function_raw_flush_stdout); register_global_function(ctx, "PLANCK_RAW_WRITE_STDERR", function_raw_write_stderr); register_global_function(ctx, "PLANCK_RAW_FLUSH_STDERR", function_raw_flush_stderr); { JSValueRef arguments[num_rest_args]; for (int i = 0; i < num_rest_args; i++) { arguments[i] = c_string_to_value(ctx, rest_args[i]); } JSValueRef args_ref = JSObjectMakeArray(ctx, num_rest_args, arguments, NULL); JSValueRef global_obj = JSContextGetGlobalObject(ctx); JSStringRef prop = JSStringCreateWithUTF8CString("PLANCK_INITIAL_COMMAND_LINE_ARGS"); JSObjectSetProperty(ctx, JSValueToObject(ctx, global_obj, NULL), prop, args_ref, kJSPropertyAttributeNone, NULL); JSStringRelease(prop); } evaluate_script(ctx, "cljs.core.set_print_fn_BANG_.call(null,PLANCK_PRINT_FN);", "<init>"); evaluate_script(ctx, "cljs.core.set_print_err_fn_BANG_.call(null,PLANCK_PRINT_ERR_FN);", "<init>"); char *elide_script = str_concat("cljs.core._STAR_assert_STAR_ = ", elide_asserts ? "false" : "true"); evaluate_script(ctx, elide_script, "<init>"); free(elide_script); { JSValueRef arguments[4]; arguments[0] = JSValueMakeBoolean(ctx, repl); arguments[1] = JSValueMakeBoolean(ctx, verbose); JSValueRef cache_path_ref = NULL; if (cache_path != NULL) { JSStringRef cache_path_str = JSStringCreateWithUTF8CString(cache_path); cache_path_ref = JSValueMakeString(ctx, cache_path_str); } arguments[2] = cache_path_ref; arguments[3] = JSValueMakeBoolean(ctx, static_fns); JSValueRef ex = NULL; JSObjectCallAsFunction(ctx, get_function(ctx, "planck.repl", "init"), JSContextGetGlobalObject(ctx), 4, arguments, &ex); debug_print_value("planck.repl/init", ctx, ex); } if (repl) { evaluate_source(ctx, "text", "(require '[planck.repl :refer-macros [apropos dir find-doc doc source pst]])", true, false, "cljs.user", "dumb"); } evaluate_script(ctx, "goog.provide('cljs.user');", "<init>"); evaluate_script(ctx, "goog.require('cljs.core');", "<init>"); evaluate_script(ctx, "cljs.core._STAR_assert_STAR_ = true;", "<init>"); // Process init arguments for (int i = 0; i < num_scripts; i++) { // TODO: exit if not successfull evaluate_source(ctx, scripts[i].type, scripts[i].source, scripts[i].expression, false, NULL, theme); } // Process main arguments if (main_ns_name != NULL) { run_main_in_ns(ctx, main_ns_name, num_rest_args, rest_args); } else if (!repl && num_rest_args > 0) { char *path = rest_args[0]; struct script script; if (strcmp(path, "-") == 0) { char *source = read_all(stdin); script.type = "text"; script.source = source; script.expression = false; } else { script.type = "path"; script.source = path; script.expression = false; } evaluate_source(ctx, script.type, script.source, script.expression, false, NULL, theme); } else if (repl) { if (!quiet) { banner(); } char *home = getenv("HOME"); char *history_path = NULL; if (home != NULL) { char history_name[] = ".planck_history"; int len = strlen(home) + strlen(history_name) + 2; history_path = malloc(len * sizeof(char)); snprintf(history_path, len, "%s/%s", home, history_name); linenoiseHistoryLoad(history_path); } char *prompt = javascript ? " > " : " => "; char *line; while ((line = linenoise(prompt)) != NULL) { if (javascript) { JSValueRef res = evaluate_script(ctx, line, "<stdin>"); print_value("", ctx, res); } else { evaluate_source(ctx, "text", line, true, true, "cljs.user", theme); } linenoiseHistoryAdd(line); if (history_path != NULL) { linenoiseHistorySave(history_path); } free(line); } } return exit_value; }
int main(int argc, char *argv[]) { // First of all, parse the IP:Port we need to connect to. // Those are for now also the only two parameters permitted. // If none passed, attempt to connect to default IP:Port. const char *ipAddress = "127.0.0.1"; uint16_t portNumber = 4040; if (argc != 1 && argc != 3) { fprintf(stderr, "Incorrect argument number. Either pass none for default IP:Port" "combination of 127.0.0.1:4040, or pass the IP followed by the Port.\n"); return (EXIT_FAILURE); } // If explicitly passed, parse arguments. if (argc == 3) { ipAddress = argv[1]; sscanf(argv[2], "%" SCNu16, &portNumber); } // Connect to the remote cAER config server. sockFd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (sockFd < 0) { fprintf(stderr, "Failed to create TCP socket.\n"); return (EXIT_FAILURE); } struct sockaddr_in configServerAddress; memset(&configServerAddress, 0, sizeof(struct sockaddr_in)); configServerAddress.sin_family = AF_INET; configServerAddress.sin_port = htons(portNumber); inet_aton(ipAddress, &configServerAddress.sin_addr); // htonl() is implicit here. if (connect(sockFd, (struct sockaddr *) &configServerAddress, sizeof(struct sockaddr_in)) < 0) { fprintf(stderr, "Failed to connect to remote config server.\n"); return (EXIT_FAILURE); } // Create a shell prompt with the IP:Port displayed. size_t shellPromptLength = (size_t) snprintf(NULL, 0, "cAER @ %s:%" PRIu16 " >> ", ipAddress, portNumber); char shellPrompt[shellPromptLength + 1]; // +1 for terminating NUL byte. snprintf(shellPrompt, shellPromptLength + 1, "cAER @ %s:%" PRIu16 " >> ", ipAddress, portNumber); // Set our own command completion function. linenoiseSetCompletionCallback(&handleCommandCompletion); // Generate command history file path (in user home). char commandHistoryFilePath[1024]; char *userHomeDir = getUserHomeDirectory(); snprintf(commandHistoryFilePath, 1024, "%s/.caerctl_history", userHomeDir); free(userHomeDir); // Load command history file. linenoiseHistoryLoad(commandHistoryFilePath); while (true) { // Display prompt and read input (NOTE: remember to free input after use!). char *inputLine = linenoise(shellPrompt); // Check for EOF first. if (inputLine == NULL) { // Exit loop. break; } // Add input to command history. linenoiseHistoryAdd(inputLine); // Then, after having added to history, check for termination commands. if (strncmp(inputLine, "quit", 4) == 0 || strncmp(inputLine, "exit", 4) == 0) { // Exit loop, free memory. free(inputLine); break; } // Try to generate a request, if there's any content. size_t inputLineLength = strlen(inputLine); if (inputLineLength > 0) { handleInputLine(inputLine, inputLineLength); } // Free input after use. free(inputLine); } // Close connection. close(sockFd); // Save command history file. linenoiseHistorySave(commandHistoryFilePath); return (EXIT_SUCCESS); }
bool process_line(repl_t *repl, char *input_line) { // Accumulate input lines if (repl->input == NULL) { repl->input = input_line; } else { repl->input = realloc(repl->input, (strlen(repl->input) + strlen(input_line) + 2) * sizeof(char)); sprintf(repl->input + strlen(repl->input), "\n%s", input_line); } repl->num_previous_lines += 1; repl->previous_lines = realloc(repl->previous_lines, repl->num_previous_lines * sizeof(char *)); repl->previous_lines[repl->num_previous_lines - 1] = strdup(input_line); // Check for explicit exit if (strcmp(repl->input, ":cljs/quit") == 0 || strcmp(repl->input, "quit") == 0 || strcmp(repl->input, "exit") == 0) { if (repl->session_id == 0) { exit_value = EXIT_SUCCESS_INTERNAL; } return true; } // Add input line to history if (repl->history_path != NULL && !is_whitespace(repl->input)) { linenoiseHistoryAdd(input_line); linenoiseHistorySave(repl->history_path); } // Check if we now have readable forms // and if so, evaluate them bool done = false; char *balance_text = NULL; while (!done) { if ((balance_text = cljs_is_readable(repl->input)) != NULL) { repl->input[strlen(repl->input) - strlen(balance_text)] = '\0'; if (!is_whitespace(repl->input)) { // Guard against empty string being read return_termsize = !config.dumb_terminal; if (repl->session_id == 0) { set_int_handler(); } // TODO: set exit value const char *theme = repl->session_id == 0 ? config.theme : "dumb"; evaluate_source("text", repl->input, true, true, repl->current_ns, theme, true, repl->session_id); if (repl->session_id == 0) { clear_int_handler(); } return_termsize = false; if (exit_value != 0) { free(repl->input); return true; } } else { printf("\n"); } // Now that we've evaluated the input, reset for next round free(repl->input); repl->input = balance_text; empty_previous_lines(repl); // Fetch the current namespace and use it to set the prompt free(repl->current_ns); free(repl->current_prompt); repl->current_ns = cljs_get_current_ns(); repl->current_prompt = form_prompt(repl->current_ns, false); if (is_whitespace(balance_text)) { done = true; free(repl->input); repl->input = NULL; } } else { // Prepare for reading non-1st of input with secondary prompt if (repl->history_path != NULL) { repl->indent_space_count = cljs_indent_space_count(repl->input); } free(repl->current_prompt); repl->current_prompt = form_prompt(repl->current_ns, true); done = true; } } return false; }