int run_repl(JSContextRef ctx) { global_ctx = ctx; current_ns = strdup("cljs.user"); current_prompt = form_prompt(current_ns, false); // Per-type initialization if (!config.dumb_terminal) { char *home = getenv("HOME"); 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); // TODO: load keymap } linenoiseSetMultiLine(1); linenoiseSetCompletionCallback(completion); linenoiseSetHighlightCallback(highlight); linenoiseSetHighlightCancelCallback(highlight_cancel); } run_cmdline_loop(ctx); return exit_value; }
// 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(); } }
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 int l_historyload(lua_State *L) { const char *filename = luaL_checkstring(L, 1); if(linenoiseHistoryLoad((char *) filename) < 0) { return handle_ln_error(L); } return handle_ln_ok(L); }
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; }
void lineedit_initialize() { memset(&l, 0, sizeof(l)); linenoiseSetMultiLine(1); /* Set the completion callback. This will be called every time the * user uses the <tab> key. */ // linenoiseSetCompletionCallback(completion); /* Load history from file. The history file is just a plain text file * where entries are separated by newlines. */ linenoiseHistoryLoad("history.txt"); }
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(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) { int firstarg; config.hostip = "127.0.0.1"; config.hostport = 6379; config.repeat = 1; config.dbnum = 0; config.interactive = 0; config.shutdown = 0; config.monitor_mode = 0; config.pubsub_mode = 0; config.raw_output = 0; config.stdinarg = 0; config.auth = NULL; config.historyfile = NULL; config.tty = isatty(fileno(stdout)) || (getenv("FAKETTY") != NULL); config.mb_sep = '\n'; if (getenv("HOME") != NULL) { config.historyfile = malloc(256); snprintf(config.historyfile,256,"%s/.rediscli_history",getenv("HOME")); linenoiseHistoryLoad(config.historyfile); } firstarg = parseOptions(argc,argv); argc -= firstarg; argv += firstarg; if (config.auth != NULL) { char *authargv[2]; int dbnum = config.dbnum; /* We need to save the real configured database number and set it to * zero here, otherwise cliSendCommand() will try to perform the * SELECT command before the authentication, and it will fail. */ config.dbnum = 0; authargv[0] = "AUTH"; authargv[1] = config.auth; cliSendCommand(2, convertToSds(2, authargv), 1); config.dbnum = dbnum; /* restore the right DB number */ } /* Start interactive mode when no command is provided */ if (argc == 0) repl(); /* Otherwise, we have some arguments to execute */ return noninteractive(argc,convertToSds(argc,argv)); }
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; }
void init_history (void) { char *home_directory; home_directory = getenv("HOME"); if (home_directory) { history_file_path = malloc(strlen(home_directory) + 2 + strlen(HISTFILE)); strcpy(history_file_path, home_directory); if (home_directory[strlen(home_directory)-1] != '/') { strcat(history_file_path, "/"); } strcat(history_file_path, HISTFILE); linenoiseHistoryLoad(history_file_path); } }
int run_repl() { repl_t *repl = make_repl(); s_repl = repl; repl->current_ns = strdup("cljs.user"); repl->current_prompt = form_prompt(repl->current_ns, false); // Per-type initialization if (!config.dumb_terminal) { char *home = getenv("HOME"); if (home != NULL) { char history_name[] = ".planck_history"; size_t len = strlen(home) + strlen(history_name) + 2; repl->history_path = malloc(len * sizeof(char)); snprintf(repl->history_path, len, "%s/%s", home, history_name); linenoiseHistoryLoad(repl->history_path); exit_value = load_keymap(home); if (exit_value != EXIT_SUCCESS) { return exit_value; } } linenoiseSetMultiLine(1); linenoiseSetCompletionCallback(completion); linenoiseSetHighlightCallback(highlight); linenoiseSetHighlightCancelCallback(highlight_cancel); } if (!config.dumb_terminal) { cljs_set_print_sender(&linenoisePrintNow); } if (config.socket_repl_port) { pthread_t thread; pthread_create(&thread, NULL, accept_connections, NULL); } run_cmdline_loop(repl); return exit_value; }
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 argc, char **argv) { int firstarg; config.filename = sdsnew("redislite.db"); config.repeat = 1; config.interactive = 0; config.stdinarg = 0; config.historyfile = NULL; config.raw_output = !isatty(fileno(stdout)) && (getenv("FAKETTY") == NULL); config.mb_delim = sdsnew("\n"); cliInitHelp(); if (getenv("HOME") != NULL) { config.historyfile = malloc(256); snprintf(config.historyfile, 256, "%s/.redislitecli_history", getenv("HOME")); linenoiseHistoryLoad(config.historyfile); } firstarg = parseOptions(argc, argv); argc -= firstarg; argv += firstarg; /* Try to connect */ if (cliConnect(0) != REDISLITE_OK) { exit(1); } /* Start interactive mode when no command is provided */ if (argc == 0) { repl(); } /* Otherwise, we have some arguments to execute */ char **converted = convertToSds(argc, argv); int ret = noninteractive(argc, converted); cliCleanHelp(); // NOTE: not free-ing converted since it may have changed inside noninteractive sdsfree(config.filename); sdsfree(config.mb_delim); redislite_close_database(db); return ret; }
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; }
int main(int argc, char **argv) { int firstarg; config.hostip = sdsnew("127.0.0.1"); config.hostport = 6379; config.hostsocket = NULL; config.repeat = 1; config.dbnum = 0; config.interactive = 0; config.shutdown = 0; config.monitor_mode = 0; config.pubsub_mode = 0; config.stdinarg = 0; config.auth = NULL; config.historyfile = NULL; config.raw_output = !isatty(fileno(stdout)) && (getenv("FAKETTY") == NULL); config.mb_delim = sdsnew("\n"); cliInitHelp(); if (getenv("HOME") != NULL) { config.historyfile = malloc(256); snprintf(config.historyfile,256,"%s/.rediscli_history",getenv("HOME")); linenoiseHistoryLoad(config.historyfile); } firstarg = parseOptions(argc,argv); argc -= firstarg; argv += firstarg; /* Try to connect */ if (cliConnect(0) != REDIS_OK) exit(1); /* Start interactive mode when no command is provided */ if (argc == 0) repl(); /* Otherwise, we have some arguments to execute */ return noninteractive(argc,convertToSds(argc,argv)); }
static int run(State& state, std::istream& in, std::ostream& out, bool interactive, bool echo) { Thread& thread = state.getMainThread(); int rc = 0; if(interactive) { linenoiseHistoryLoad((char*)".riposte_history"); } bool done = false; while(!done) { try { Value code; done = interactive ? terminal(state, in, out, code) : pipe(state, in, out, code); if(done || code.isNil()) continue; Prototype* proto = Compiler::compileTopLevel(thread, code); Value result = thread.eval(proto, state.global); if(echo) out << state.stringify(result) << std::endl; } catch(RiposteException& e) { e_message("Error", e.kind().c_str(), e.what().c_str()); } dumpWarnings(thread, out); } return rc; }
SEXP R_readline_read_line(SEXP prompt, SEXP multiline, SEXP history, SEXP completions) { char *line; SEXP result; linenoiseSetEncodingFunctions( linenoiseUtf8PrevCharLen, linenoiseUtf8NextCharLen, linenoiseUtf8ReadCode); if (!isNull(history)) linenoiseHistoryLoad(CHAR(STRING_ELT(history, 0))); if (!isNull(completions)) { R_readline_completions = completions; linenoiseSetCompletionCallback(R_readline_completion); } linenoiseSetMultiLine(LOGICAL(multiline)[0]); line = linenoise(CHAR(STRING_ELT(prompt, 0))); result = ScalarString(mkCharCE(line, CE_UTF8)); free(line); return result; }
int read_history(const char *filename) { return -1 != linenoiseHistoryLoad(filename != NULL ? (char *)filename : DEFAULT_HISTORY_FILE) ? 0 : errno; }
int main(int argc, char **argv) { int i; int opt; char *pi = NULL; char *po = NULL; if (argc < 2) { usage(); exit(-1); } printf("PERS CLI started with arguments:"); for (i = 0 ; i < argc; i++) printf(" %s", argv[i]); printf("\n"); while (-1 != (opt = getopt(argc, argv, "i:o:h"))) { switch (opt) { case 'h': usage(); return 0; case 'i': pi = optarg; break; case 'o': po = optarg; break; default: printf("unsupported option received\n"); return -1; } } if (!pi) { fprintf(stderr, "Input pipe not specified\n"); exit(-1); } if (!po) { fprintf(stderr, "Output pipe not specified\n"); exit(-1); } fo = fopen(po, "w"); if (!fo) { fprintf(stderr, "Error opening file '%s' for writing\n", po); exit(-1); } fi = fopen(pi, "r"); if (!fi) { fprintf(stderr, "Error opening file '%s' for reading\n", pi); exit(-1); } if (personnel_param_init()) { printf("personnel_param_init() failed\n"); return -1; } linenoiseSetCompletionCallback(completion); linenoiseHistoryLoad("history.txt"); /* Load the history at startup */ /* Loop reading stdin */ readlines(); if (fi != stdin) fclose(fi); if ((fo != stdout) && (fo != stderr)) fclose(fo); printf("Halting the CLI\n"); exit: mpl_param_system_deinit(); printf("DONE\n"); return 0; }
int main(int argc, char **argv) { int i; int opt; char *pi = NULL; char *po = NULL; printf("TESTPROT CLI started with arguments:"); for (i = 0 ; i < argc; i++) printf(" %s", argv[i]); printf("\n"); while (-1 != (opt = getopt(argc, argv, "i:o:h"))) { switch (opt) { case 'h': printf("Usage: testprot_cli <options>\n"); printf(" -h Show command usage\n"); printf(" -i input pipe\n"); printf(" -o output pipe\n"); return 0; case 'i': pi = optarg; break; case 'o': po = optarg; break; default: printf("unsupported option received\n"); return -1; } } if (po) { fo = fopen(po, "w"); if (!fo) { fprintf(stderr, "Error opening file '%s' for writing\n", po); exit(-1); } } else { fo = stdout; } if (pi) { fi = fopen(pi, "r"); if (!fi) { fprintf(stderr, "Error opening file '%s' for reading\n", pi); exit(-1); } } else { fi = stdin; } if (testprotocol_param_init()) { printf("testprotocol_param_init() failed\n"); return -1; } linenoiseSetCompletionCallback(completion); linenoiseHistoryLoad("history.txt"); /* Load the history at startup */ /* Loop reading stdin */ readlines(); if (fi != stdin) fclose(fi); if ((fo != stdout) && (fo != stderr)) fclose(fo); printf("Halting the CLI\n"); exit: mpl_param_deinit(); printf("DONE\n"); 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_HistoryLoad(const char *filename) { #ifdef USE_LINENOISE linenoiseHistoryLoad(filename); #endif }
bool Console::loadHistory(const std::string& fileName) { return linenoiseHistoryLoad(fileName.c_str()) == 0; }
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); }
/* 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[]) { 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; }