Exemple #1
0
static gboolean
process_arguments (int *argc, char ***argv,
                   GError **error)
{
  GOptionContext *context;
  gboolean ret;
  GOptionGroup *group;

  group = g_option_group_new (NULL, /* name */
                              NULL, /* description */
                              NULL, /* help_description */
                              NULL, /* user_data */
                              NULL /* destroy notify */);
  g_option_group_add_entries (group, options);
  context = g_option_context_new ("- A server for practicing a "
                                  "foreign language");
  g_option_context_set_main_group (context, group);
  ret = g_option_context_parse (context, argc, argv, error);
  g_option_context_free (context);

  if (ret && *argc > 1)
    {
      g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_UNKNOWN_OPTION,
                   "Unknown option '%s'", (* argv)[1]);
      ret = FALSE;
    }

  return ret;
}
int
main( int argc, char *argv[] )
{
	GOptionContext *context;
	GOptionGroup *main_group;
	GError *error = NULL;

	if( VIPS_INIT( argv[0] ) )
	        vips_error_exit( "unable to start VIPS" );

	textdomain( GETTEXT_PACKAGE );
	setlocale( LC_ALL, "" );

        context = g_option_context_new( _( "- introspect" ) );
	main_group = g_option_group_new( NULL, NULL, NULL, NULL, NULL );
	g_option_group_add_entries( main_group, main_option );
	vips_add_option_entries( main_group ); 
	g_option_group_set_translation_domain( main_group, GETTEXT_PACKAGE );
	g_option_context_set_main_group( context, main_group );

	if( !g_option_context_parse( context, &argc, &argv, &error ) ) {
		if( error ) {
			fprintf( stderr, "%s\n", error->message );
			g_error_free( error );
		}

		vips_error_exit( "try \"%s --help\"", g_get_prgname() );
	}

	g_option_context_free( context );

#ifdef DEBUG
	/* For debugging it's handy to have a copy of the input file.
	 */
	if( main_option_introspect_dump ) { 
		char **args;
		char *cmd;

		args = g_strsplit( main_option_introspect_dump, ",", 2 );
		cmd = g_strdup_printf( "cp %s ~/functions.txt", args[0]);
		printf( "introspect: running '%s'\n", cmd );
		system( cmd );
		g_free( cmd );
	}
#endif /*DEBUG*/

	if( main_option_introspect_dump &&
		!g_irepository_dump( main_option_introspect_dump, &error ) ) {
		if( error ) {
			fprintf( stderr, "%s\n", error->message );
			g_error_free( error );
		}

		vips_error_exit( "unable to dump introspection" ); 
	}

	vips_shutdown();

	return( 0 );
}
Exemple #3
0
void
mu_config_show_help (MuConfigCmd cmd)
{
	GOptionContext *ctx;
	GOptionGroup *group;
	char *cleanhelp;

	g_return_if_fail (mu_config_cmd_is_valid(cmd));

	ctx = g_option_context_new ("");
	g_option_context_set_main_group	(ctx, config_options_group_mu());

	group = get_option_group (cmd);
	if (group)
		g_option_context_add_group (ctx, group);

	g_option_context_set_description (ctx,
					  get_help_string (cmd, TRUE));
	cleanhelp = massage_help
		(g_option_context_get_help (ctx, TRUE, group));

	g_print ("usage:\n\t%s\n%s",
		 get_help_string (cmd, FALSE), cleanhelp);

	g_free (cleanhelp);
}
/**
 * gdict_debug_init:
 * @argc: FIXME
 * @argv: FIXME
 *
 * FIXME
 *
 * Since: 0.12
 */
void
gdict_debug_init (gint    *argc,
                  gchar ***argv)
{
  GOptionContext *option_context;
  GOptionGroup *gdict_group;
  GError *error = NULL;

  if (gdict_is_initialized)
    return;

  option_context = g_option_context_new (NULL);
  g_option_context_set_ignore_unknown_options (option_context, TRUE);
  g_option_context_set_help_enabled (option_context, FALSE); 

  gdict_group = gdict_get_option_group ();
  g_option_context_set_main_group (option_context, gdict_group);

  if (!g_option_context_parse (option_context, argc, argv, &error))
    {
      g_warning ("%s", error->message);
      g_error_free (error);
    }

  g_option_context_free (option_context);
}
Exemple #5
0
static gboolean
tf_graphite_parse_command_line_arguments(TFGraphiteState *self, gint *argc, gchar ***argv, LogTemplate *parent)
{
  GOptionContext *ctx;
  GOptionGroup *og; 
  TFGraphiteArgumentsUserData userdata;
  gboolean success;
  GError *error = NULL;

  GOptionEntry graphite_options[] = {
     { "timestamp", 't', 0, G_OPTION_ARG_CALLBACK, tf_graphite_set_timestamp, NULL, NULL }, 
     { NULL },
  };

  userdata.state = self;
  userdata.cfg = parent->cfg;

  ctx = g_option_context_new ("graphite-options");
  og = g_option_group_new (NULL, NULL, NULL, &userdata, NULL);
  g_option_group_add_entries(og, graphite_options);
  g_option_context_set_main_group(ctx, og); 
  g_option_context_set_ignore_unknown_options(ctx, TRUE);

  success = g_option_context_parse (ctx, argc, argv, &error);
  g_option_context_free (ctx);

  return success;
}
/**
 * Main function for command-line filter utility.
 */
int main(int argc, char *argv[]) 
{
#ifndef HAVE_G_OPTION_GROUP
  printf("Need GLib >= 2.6\n");
#else

  GError *error;
  GOptionContext *context;
  char inFilename[FLEN_FILENAME], outFilename[FLEN_FILENAME];
  oi_fits inData, outData;
  int status;

  /* Parse command-line */
  error = NULL;
  context =
    g_option_context_new("INFILE OUTFILE - write filtered dataset to new file");
  g_option_context_set_main_group(context, get_oi_filter_option_group());
  g_option_context_parse(context, &argc, &argv, &error);
  if(error != NULL) {
    printf("Error parsing command-line options: %s\n", error->message);
    g_error_free(error);
    exit(2); /* standard unix behaviour */
  }
  if(argc != 3) {
    printf("Wrong number of command-line arguments\n"
	   "Enter '%s --help' for usage information\n", argv[0]);
    exit(2);
  }
  g_strlcpy(inFilename, argv[1], FLEN_FILENAME);
  g_strlcpy(outFilename, argv[2], FLEN_FILENAME);

  /* Read FITS file */
  status = 0;
  read_oi_fits(inFilename, &inData, &status);
  if(status) goto except;

  /* Display summary info */
  printf("=== INPUT DATA: ===\n");
  print_oi_fits_summary(&inData);
  printf("=== Applying filter: ===\n");
  print_oi_filter(get_user_oi_filter());

  /* Apply filter */
  apply_user_oi_filter(&inData, &outData);
  printf("--> OUTPUT DATA: ===\n");
  print_oi_fits_summary(&outData);

  /* Write out filtered data */
  write_oi_fits(outFilename, outData, &status);
  if(status) goto except;

  free_oi_fits(&inData);
  free_oi_fits(&outData);
  g_option_context_free(context);
  exit(EXIT_SUCCESS);

 except:
  exit(EXIT_FAILURE);
#endif /* #ifndef HAVE_G_OPTION_GROUP */
}
Exemple #7
0
static gboolean
parse_params (int *argcp, char ***argvp, GError **err)
{
	GOptionContext *context;
	GOptionGroup *group;
	gboolean rv;

	context = g_option_context_new("- mu general options");
	g_option_context_set_help_enabled (context, TRUE);

	err = NULL;
	rv  = TRUE;

	g_option_context_set_main_group(context,
					config_options_group_mu());

	switch (MU_CONFIG.cmd) {
	case MU_CONFIG_CMD_NONE: show_usage(); break;
	case MU_CONFIG_CMD_HELP:
		/* 'help' is special; sucks in the options of the
		 * command after it */
		rv = g_option_context_parse (context, argcp, argvp, err) &&
			cmd_help ();
		break;
	default:
		group = get_option_group (MU_CONFIG.cmd);
		if (group)
			g_option_context_add_group(context, group);
		rv = g_option_context_parse (context, argcp, argvp, err);
	}
	g_option_context_free (context);

	return rv ? TRUE : FALSE;
}
Exemple #8
0
void
gegl_init (gint    *argc,
           gchar ***argv)
{
  GOptionContext *context;
  GError         *error = NULL;
  static gboolean initialized = FALSE;

  if (initialized)
    return;

  initialized = TRUE;

  context = g_option_context_new (NULL);
  g_option_context_set_ignore_unknown_options (context, TRUE);
  g_option_context_set_help_enabled (context, FALSE);
  g_option_context_set_main_group (context, gegl_get_option_group ());

  if (!g_option_context_parse (context, argc, argv, &error))
    {
      g_warning ("%s", error->message);
      g_error_free (error);
    }

  g_option_context_free (context);
}
Exemple #9
0
static gboolean
parse_params (int *argcp, char ***argvp)
{
	GError *err;
	GOptionContext *context;
	gboolean rv;

	context = g_option_context_new("- mu general options");
	g_option_context_set_main_group(context, config_options_group_mu());
	g_option_context_set_help_enabled (context, TRUE);

	err = NULL;

	/* help is special */
	if (MU_CONFIG.cmd == MU_CONFIG_CMD_HELP) {
		rv = g_option_context_parse (context, argcp, argvp, &err) &&
			init_cmd_help (&err);
	} else {
		GOptionGroup *group;
		group = get_option_group (MU_CONFIG.cmd);
		if (group)
			g_option_context_add_group(context, group);
		rv = g_option_context_parse (context, argcp, argvp, &err);
	}

	g_option_context_free (context);
	if (!rv) {
		g_printerr ("mu: error in options: %s\n",
			    err ? err->message : "?");
		g_clear_error (&err);
		return FALSE;
	}

	return TRUE;
}
Exemple #10
0
Fichier : gdk.c Projet : 3v1n0/gtk
/**
 * gdk_parse_args:
 * @argc: the number of command line arguments.
 * @argv: (inout) (array length=argc): the array of command line arguments.
 * 
 * Parse command line arguments, and store for future
 * use by calls to gdk_display_open().
 *
 * Any arguments used by GDK are removed from the array and @argc and @argv are
 * updated accordingly.
 *
 * You shouldn’t call this function explicitly if you are using
 * gtk_init(), gtk_init_check(), gdk_init(), or gdk_init_check().
 *
 * Since: 2.2
 **/
void
gdk_parse_args (int    *argc,
                char ***argv)
{
  GOptionContext *option_context;
  GOptionGroup *option_group;
  GError *error = NULL;

  if (gdk_initialized)
    return;

  gdk_pre_parse ();

  option_context = g_option_context_new (NULL);
  g_option_context_set_ignore_unknown_options (option_context, TRUE);
  g_option_context_set_help_enabled (option_context, FALSE);
  option_group = g_option_group_new (NULL, NULL, NULL, NULL, NULL);
  g_option_context_set_main_group (option_context, option_group);

  g_option_group_add_entries (option_group, gdk_args);

  if (!g_option_context_parse (option_context, argc, argv, &error))
    {
      g_warning ("%s", error->message);
      g_error_free (error);
    }
  g_option_context_free (option_context);

  GDK_NOTE (MISC, g_message ("progname: \"%s\"", g_get_prgname ()));
}
Exemple #11
0
static CoglBool
process_arguments (int *argc, char ***argv,
                   GError **error)
{
  GOptionContext *context;
  CoglBool ret;
  GOptionGroup *group;

  group = g_option_group_new (NULL, /* name */
                              NULL, /* description */
                              NULL, /* help_description */
                              NULL, /* user_data */
                              NULL /* destroy notify */);
  g_option_group_add_entries (group, options);
  context = g_option_context_new ("- An example Wayland compositor using Cogl");
  g_option_context_set_main_group (context, group);
  ret = g_option_context_parse (context, argc, argv, error);
  g_option_context_free (context);

  if (ret && *argc > 1)
    {
      g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_UNKNOWN_OPTION,
                   "Unknown option '%s'", (* argv)[1]);
      ret = FALSE;
    }

  return ret;
}
Exemple #12
0
void tg_option_tests()
{

	GOptionContext *context;
	GOptionContext *context1;//for testing set main group
	GOptionContext *context2;//for testing add group
	gboolean retval;
	GError *error = NULL;
	gchar **argv;
	int argc;
	gchar **argv1;
	int argc1;
	GOptionEntry entries [] =
	    { { "test", 0, 0, G_OPTION_ARG_INT, &arg_test1_int, "test_description", "test_arg" },
	      { NULL } };
	GOptionEntry entries1 [] =
	    { { "try", 0, 0, G_OPTION_ARG_INT, &arg_test1_int, "try_description", "try_arg" },
	      { NULL } };
	GOptionEntry entries2 [] =
	    { { "again", 0, 0, G_OPTION_ARG_INT, &arg_test1_int, "again_description", "again_arg" },
	      { NULL } };
	
	GOptionGroup *main_group;
		
	context = g_option_context_new (NULL);
	context1 = g_option_context_new (NULL);
	context2 = g_option_context_new (NULL);
	g_option_context_add_main_entries (context, entries, NULL);
	g_option_context_add_main_entries (context2, entries, NULL);
  	
  	main_group = g_option_context_get_main_group (context);
  	//Testing g_option_context_set_main_group with another context-context1
	g_option_group_add_entries (main_group,entries1);
	g_option_context_set_main_group(context1,main_group);

	//Testing g_option_context_set_help_enabled 
	//and g_option_context_get_help_enabled
	//and g_option_context_get_ignore_unknown_options
	g_option_context_set_help_enabled(context,TRUE);
	g_assert(g_option_context_get_help_enabled(context));
	g_assert(!g_option_context_get_ignore_unknown_options(context));
	
	/* Now try parsing on context1*/
	argv = split_string ("program --try 20 --try 30", &argc);
	  
	retval = g_option_context_parse (context1, &argc, &argv, &error);
	g_assert (retval);

	/* Last arg specified is the one that should be stored */
	g_assert (arg_test1_int == 30);

	g_option_group_set_error_hook (main_group, error_func);
	argv = split_string ("program --none 20 --none 30", &argc);
	retval = g_option_context_parse (context1, &argc, &argv, &error);
		
	g_strfreev (argv);
	g_option_context_free (context);
	  
}
Exemple #13
0
int main (int argc, char* argv[])
{
	const UgOptionEntry*	uoentry;
	UgDataset*		dataset;
	UgetCommon*	common;
	UgPlugin*		plugin;

	GOptionContext*	context;
	GOptionGroup*	group;
	GError*			error = NULL;

#ifdef _WIN32	//	curl_global_init() will do this
	WSADATA WSAData;

	WSAStartup (MAKEWORD (2, 2), &WSAData);
#endif

	uglib_init ();

	// parse command-line options
	context = g_option_context_new ("[URL]");
	group	= g_option_group_new (NULL, NULL, NULL, NULL, NULL);
	uoentry = ug_option_get_main_entry ();
	g_option_group_add_entries (group, uoentry->entry);
	g_option_context_set_main_group (context, group);
	if (g_option_context_parse (context, &argc, &argv, &error) == FALSE) {
		g_print ("Option parsing failed : %s\n", error->message);
		exit (EXIT_FAILURE);		// EXIT_FAILURE == 1
	}

	// get URL from remained arguments
	if (argc == 1) {
		g_print ("%s", g_option_context_get_help (context, TRUE, NULL));
		exit (EXIT_FAILURE);		// EXIT_FAILURE == 1
	}
	dataset = ug_dataset_new ();
	ug_option_entry_get (uoentry, dataset);
	common = ug_dataset_realloc (dataset, UgetCommonInfo, 0);
	common->url = g_strdup (argv[1]);

	plugin = ug_plugin_new_by_data (dataset);
	ug_dataset_unref (dataset);
	if (plugin) {
		ug_plugin_set_state (plugin, UG_STATE_ACTIVE);
		while (ug_plugin_dispatch (plugin, plugin_callback, NULL))
			ug_plugin_delay (plugin, 1000);
		ug_plugin_unref (plugin);
	}

	uglib_finalize ();
#ifdef _WIN32
	WSACleanup ();
#endif

	return EXIT_SUCCESS;		// EXIT_SUCCESS == 0
}
Exemple #14
0
int main(int argc, char *argv[])
{
    GError *error = NULL;
    GOptionContext *context;

    signal(SIGINT, signal_handler);

    /* parse opts */
    context = g_option_context_new(NULL);
    g_option_context_set_summary(context, "A Spice client used for testing and measurements.");
    g_option_context_set_description(context, "Report bugs to " PACKAGE_BUGREPORT ".");
    g_option_context_set_main_group(context, spice_cmdline_get_option_group());
    g_option_context_add_main_entries(context, app_entries, NULL);
    if (!g_option_context_parse (context, &argc, &argv, &error)) {
        g_print("option parsing failed: %s\n", error->message);
        exit(1);
    }

    if (version) {
        g_print("spicy-stats " PACKAGE_VERSION "\n");
        exit(0);
    }

    mainloop = g_main_loop_new(NULL, false);

    session = spice_session_new();
    g_signal_connect(session, "channel-new",
                     G_CALLBACK(channel_new), NULL);
    spice_cmdline_session_setup(session);

    if (!spice_session_connect(session)) {
        fprintf(stderr, "spice_session_connect failed\n");
        exit(1);
    }

    g_main_loop_run(mainloop);
    {
        GList *iter, *list = spice_session_get_channels(session);
        gulong total_read_bytes;
        gint  channel_type;
        printf("total bytes read:\n");
        for (iter = list ; iter ; iter = iter->next) {
            g_object_get(iter->data,
                "total-read-bytes", &total_read_bytes,
                "channel-type", &channel_type,
                NULL);
            printf("%s: %lu\n",
                   spice_channel_type_to_string(channel_type),
                   total_read_bytes);
        }
        g_list_free(list);
    }
    return 0;
}
Exemple #15
0
static gboolean
parse_cmdline (struct config *cfg, gint *argc, gchar **argv[], GError **error)
{
    GOptionContext *context;
    GOptionEntry entries[] =
    {
        { "category",           'c',    0, G_OPTION_ARG_CALLBACK,   cmdline_category,
            "Set the item's category;\n\t\t"
                "CATEGORY must be app, comm, system or hardware", "CATEGORY" },
        { "title",              't',    0, G_OPTION_ARG_STRING,     &cfg->title,
            "Set TITLE as the item's title", "TITLE" },
        { "status",             's',    0, G_OPTION_ARG_CALLBACK,   cmdline_status,
            "Set the item's status;\n\t\t"
                "STATUS must be active, passive or attention", "STATUS" },
        { "icon",               'i',    0, G_OPTION_ARG_CALLBACK,   cmdline_icon_name,
            "Use NAME as icon name for (main) icon", "NAME" },
        { "pixbuf",             'I',    0, G_OPTION_ARG_CALLBACK,   cmdline_icon_pixbuf,
            "Load FILE as icon for (main) icon", "FILE" },
        { "attention-icon",     'a',    0, G_OPTION_ARG_CALLBACK,   cmdline_icon_name,
            "Use NAME as icon name for attention icon", "NAME" },
        { "attention-pixbuf",   'A',    0, G_OPTION_ARG_CALLBACK,   cmdline_icon_pixbuf,
            "Load FILE as icon for attention icon", "FILE" },
        { "overlay-icon",       'o',    0, G_OPTION_ARG_CALLBACK,   cmdline_icon_name,
            "Use NAME as icon name for overlay icon", "NAME" },
        { "overlay-pixbuf",     'O',    0, G_OPTION_ARG_CALLBACK,   cmdline_icon_pixbuf,
            "Load FILE as icon for overlay icon", "FILE" },
        { "tooltip-icon",       'l',    0, G_OPTION_ARG_CALLBACK,   cmdline_icon_name,
            "Use NAME as icon name for tooltip icon", "NAME" },
        { "tooltip-pixbuf",     'L',    0, G_OPTION_ARG_CALLBACK,   cmdline_icon_pixbuf,
            "Load FILE as icon for tooltip icon", "FILE" },
        { "tooltip",            'T',    0, G_OPTION_ARG_STRING,     &cfg->tooltip_title,
            "Set TITLE as title of the item's tooltip", "TITLE" },
        { "tooltip-body",       'b',    0, G_OPTION_ARG_STRING,     &cfg->tooltip_body,
            "Set TEXT as body of the item's tooltip", "TEXT" },
        { "item-is-menu",       'M',    0, G_OPTION_ARG_NONE,       &cfg->item_is_menu,
            "Whether the item only supports context menu or not", NULL},
#ifdef USE_DBUSMENU
        { "dbus-menu",          'm',    0, G_OPTION_ARG_NONE,       &cfg->menu,
            "Whether menu should be exposed via dbusmenu or not", NULL },
#endif
        { NULL }
    };
    GOptionGroup *group;

    context = g_option_context_new ("");
    group = g_option_group_new ("example", "example", "app options", cfg, NULL);
    g_option_group_add_entries (group, entries);
    g_option_context_set_main_group (context, group);
    if (!g_option_context_parse (context, argc, argv, error))
        return FALSE;

    return TRUE;
}
Exemple #16
0
static gboolean
parse_params (int *argcp, char ***argvp, GError **err)
{
	GOptionContext *context;
	GOptionGroup *group;
	gboolean rv;

	context = g_option_context_new("- mu general options");

	g_option_context_set_help_enabled (context, TRUE);
	rv  = TRUE;

	g_option_context_set_main_group(context,
					config_options_group_mu());
	g_option_context_set_ignore_unknown_options (context, FALSE);

	switch (MU_CONFIG.cmd) {
	case MU_CONFIG_CMD_NONE:
		show_usage();
		break;
	case MU_CONFIG_CMD_HELP:
		/* 'help' is special; sucks in the options of the
		 * command after it */
		rv = g_option_context_parse (context, argcp, argvp, err) &&
			cmd_help ();
		break;
	case MU_CONFIG_CMD_SCRIPT:
		/* all unknown commands are passed to 'script' */
		g_option_context_set_ignore_unknown_options (context, TRUE);
		group = get_option_group (MU_CONFIG.cmd);
		g_option_context_add_group (context, group);
		rv  = g_option_context_parse (context, argcp, argvp, err);
		MU_CONFIG.script = g_strdup (MU_CONFIG.cmdstr);
		/* argvp contains the script parameters */
		MU_CONFIG.script_params = (const char**)&((*argvp)[1]);
		break;

	default:
		group = get_option_group (MU_CONFIG.cmd);
		if (group)
			g_option_context_add_group (context, group);

		rv = g_option_context_parse (context, argcp, argvp, err);
		break;
	}

	g_option_context_free (context);

	return rv ? TRUE : FALSE;
}
Exemple #17
0
Fichier : ttx.c Projet : djcb/ttx
static gboolean
process_options (Opts *opts, int *argcp, char ***argvp, GError **err)
{
        gboolean rv;
        GOptionContext *octx;

        octx = g_option_context_new ("- ttx options");

        g_option_context_set_main_group (octx, get_option_group(opts));
        rv = g_option_context_parse (octx, argcp, argvp, err);
        g_option_context_free (octx);

        return rv;
}
int
main (int argc, char *argv[])
{
  GOptionContext *option_context;
  GOptionGroup *option_group;
  GError *error = NULL;

  g_type_init ();

  option_group = g_option_group_new ("ephy-profile-migrator",
                                     N_("Epiphany profile migrator"),
                                     N_("Epiphany profile migrator options"),
                                     NULL, NULL);

  g_option_group_set_translation_domain (option_group, GETTEXT_PACKAGE);
  g_option_group_add_entries (option_group, option_entries);

  option_context = g_option_context_new ("");
  g_option_context_set_main_group (option_context, option_group);

  if (!g_option_context_parse (option_context, &argc, &argv, &error)) {
    g_print ("Failed to parse arguments: %s\n", error->message);
    g_error_free (error);
    g_option_context_free (option_context);

    return 1;
  }
        
  g_option_context_free (option_context);

  ephy_debug_init ();

  if (!ephy_file_helpers_init (NULL, EPHY_FILE_HELPERS_NONE, NULL)) {
    LOG ("Something wrong happened with ephy_file_helpers_init()");
    return -1;
  }

  return ephy_migrator () ? 0 : 1;
}
Exemple #19
0
static gboolean
process_arguments (int *argc,
                   char ***argv,
                   GError **error)
{
    GOptionContext *context;
    gboolean ret;
    GOptionGroup *group;

    group = g_option_group_new (NULL, /* name */
                                NULL, /* description */
                                NULL, /* help_description */
                                NULL, /* user_data */
                                NULL /* destroy notify */);
    g_option_group_add_entries (group, options);
    context = g_option_context_new ("- Verifies a signed data file "
                                    "with the given key");
    g_option_context_set_main_group (context, group);
    ret = g_option_context_parse (context, argc, argv, error);
    g_option_context_free (context);

    if (ret)
    {
        if (*argc > 1)
        {
            g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_UNKNOWN_OPTION,
                         "Unknown option '%s'", (* argv)[1]);
            ret = FALSE;
        }
        else if (option_data_file == NULL || option_data_file == NULL)
        {
            g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
                         "The -k and -d options are required. See --help");
            ret = FALSE;
        }
    }

    return ret;
}
Exemple #20
0
static gboolean
init_cmd_help (GError **err)
{
	MuConfigCmd cmd;
	GOptionContext *ctx;
	GOptionGroup *group;
	char *cleanhelp;

	if (!MU_CONFIG.params ||
	    !MU_CONFIG.params[0] || !MU_CONFIG.params[1] ||
	    MU_CONFIG.params[2])
		goto errexit;

	cmd = cmd_from_string (MU_CONFIG.params[1]);
	if (cmd == MU_CONFIG_CMD_UNKNOWN)
		goto errexit;

	ctx = g_option_context_new ("");
	g_option_context_set_main_group
		(ctx, config_options_group_mu());
	group = get_option_group (cmd);
	if (group)
		g_option_context_add_group (ctx, group);

	g_option_context_set_description (ctx, cmd_help (cmd, TRUE));
	cleanhelp = massage_help
		(g_option_context_get_help (ctx, TRUE, group));

	g_print ("Usage:\n\t%s\n%s",
		 cmd_help (cmd, FALSE), cleanhelp);
	g_free (cleanhelp);

	return TRUE;

errexit:
	mu_util_g_set_error (err, MU_ERROR_IN_PARAMETERS,
			     "usage: mu help <command>");
	return FALSE;
}
Exemple #21
0
static gboolean
parse_params (MuConfig *opts, int *argcp, char ***argvp)
{
	GError *err = NULL;
	GOptionContext *context;
	gboolean rv;

	context = g_option_context_new("- mu general option");
	g_option_context_set_main_group(context,
					config_options_group_mu(opts));

	add_context_group (context, opts);

	rv = g_option_context_parse (context, argcp, argvp, &err);
	g_option_context_free (context);
	if (!rv) {
		g_printerr ("mu: error in options: %s\n", err->message);
		g_error_free (err);
		return FALSE;
	}
	return TRUE;
}
Exemple #22
0
int main(int argc, char *argv[]){
    GError *error = NULL;
    GOptionContext *context;
    context = g_option_context_new("glib option test");

    GOptionGroup *main_group = g_option_group_new("main", 
                                  "Main options", 
                                  "Main options",
                                  NULL, NULL);

    g_option_group_add_entries(main_group, common_entries);
    g_option_context_set_main_group(context, main_group);

    if (!g_option_context_parse(context, &argc, &argv, &error)){
        g_print ("option parsing failed: %s, try --help\n", error->message);
        exit (EXIT_FAILURE);
    }

    MYSQL *conn;
    conn = create_main_connection();
    start_dump(conn);
    g_option_context_free(context);
    return 0;
}
Exemple #23
0
/**
 * gegl_init:
 * @argc: a pointer to the number of command line arguments.
 * @argv: a pointer to the array of command line arguments.
 *
 * Call this function before using any other GEGL functions. It will initialize
 * everything needed to operate GEGL and parses some standard command line
 * options.  @argc and @argv are adjusted accordingly so your own code will
 * never see those standard arguments.
 *
 * Note that there is an alternative ways to initialize GEGL: if you are
 * calling g_option_context_parse() with the option group returned by
 * gegl_get_option_group(), you don't have to call gegl_init().
 **/
void
gegl_init (gint    *argc,
           gchar ***argv)
{
  GOptionContext *context;
  GError         *error = NULL;
  if (config)
    return;

  /*  If any command-line actions are ever added to GEGL, then the commented
   *  out code below should be used.  Until then, we simply call the parse hook
   *  directly.
   */
#if 0
  gegl_post_parse_hook (NULL, NULL, NULL, NULL);
#else

  context = g_option_context_new (NULL);
  g_option_context_set_ignore_unknown_options (context, TRUE);
  g_option_context_set_help_enabled (context, FALSE);
  g_option_context_set_main_group (context, gegl_get_option_group ());

  if (!g_option_context_parse (context, argc, argv, &error))
    {
      g_warning ("%s", error->message);
      g_error_free (error);
    }

  g_option_context_free (context);
#endif

  /* Not the best place for this ... better to put it in post_parse and just
   * save argv[0] here.
   */
  vips_init (*argv[0]);
}
SSVCommandLine *
ssv_command_line_new (gint *argc, gchar ***argv)
{
  SSVCommandLine *self = g_new (SSVCommandLine, 1);

  // Initialize the contents of the structure we will parse into with
  // default or empty values.  IMPROVEME: this notion of the default
  // cache directory is manually synced with some code in main().
  self->cache_dir = g_string_new (getenv ("HOME"));
  g_string_append (self->cache_dir, "/.ssv_cache");
  const gint default_max_cache_size = 400;
  self->max_cache_size = default_max_cache_size;
  self->pixmaps = pix_maps_spec_new ();
  // If sigmas is negative, we will try to linearly map the whole range.
  const gdouble default_sigmas = 2.0;
  self->sigmas = default_sigmas;
  self->images = g_ptr_array_new ();
  self->x_offsets = g_array_new (FALSE, FALSE, sizeof (gint));
  self->y_offsets = g_array_new (FALSE, FALSE, sizeof (gint));
  gchar *analysis_program = NULL;  // We'll copy into GString in self later.
  self->async_analysis = FALSE;
  const gint default_analysis_tile_size = 51;
  self->analysis_tile_size = default_analysis_tile_size;

  const gint option_type_count = 8;
  // List of uptions (+1 for the 'option' which handles the arguments,
  // +1 for the one with NULL for its long_name which terminated the
  // list).
  GOptionEntry *entries = g_new (GOptionEntry, option_type_count + 1 + 1);

  // Place for the parser to store the cache directory option argument
  // value.  It looks like the option parser automagicly allocates
  // this.
  gchar *cache_dir = NULL;

  // Place for the parser to store the image file names.
  gchar **image_names = NULL;

  // Entry strings, including documentation that gets printed by
  // --help (make sure it still looks good after changes).

  // IMPROVEME: there are little bits in these documentation strings
  // that at the moment need to be manually kept in sync with the
  // defaults and such.

  entries[0].long_name = "cache-dir";
  entries[0].short_name = 'c';
  entries[0].flags = 0;
  entries[0].arg = G_OPTION_ARG_FILENAME;
  entries[0].arg_data  = &cache_dir;
  entries[0].description
    = "\n     Directory to use for pyramid cache (defualt: ~/.ssv_cache)\n";
  entries[0].arg_description = "DIRECTORY";

  entries[1].long_name = "max-cache-size";
  entries[1].short_name = 'm';
  entries[1].flags = 0;
  entries[1].arg = G_OPTION_ARG_INT;
  entries[1].arg_data = &(self->max_cache_size);
  entries[1].description
    = (
"\n     Maximum cache size, in megabytes.  Old (unused) entries start\n"
"     getting deleted when the cache gets this big.  Default is 400.\n");
  entries[1].arg_description = "SIZE";
    
  entries[2].long_name = "pixmap";
  entries[2].short_name = 'p';
  entries[2].flags = 0;
  entries[2].arg = G_OPTION_ARG_CALLBACK;
  entries[2].arg_data = parse_pixmap;
  entries[2].description
    = (
"\n     Pixel remap specification of the form \"[a,b],c\".  Pixels in the \n"
"     range [a,b] (values of \"nan\" or \"inf\" are allowed) are not \n"
"     considerd when computing the image statistics used to map the image \n"
"     into the representable range of pixel values, and are always \n"
"     represented visually as if they have value c.  Note that pixel maps\n"
"     have no effect at all on pixel information, tile analysis, etc.: they\n"
"     only affect how the image data is rendered\n");
  entries[2].arg_description = "SPEC";

  entries[3].long_name = "sigmas";
  entries[3].short_name = 's';
  entries[3].flags = 0;
  entries[3].arg = G_OPTION_ARG_DOUBLE;
  entries[3].arg_data = &(self->sigmas);
  entries[3].description
    = (
"\n     When displaying data, map values within SIGMAS standard deviations\n"
"     of the mean linearly into the displayable range of values, and clamp\n"
"     values outside this region to the endpoints of the displayable range.\n"
"     Note that sufficiently huge or special pixel values will still require\n"
"     the use of pixel maps (see --pixmap option description).  The default\n"
"     value is 2.0.  If SIGMAS is negative, the whole range of pixel values\n"
"     present in the data will be mapped linearly into the displayable\n"
"     range.\n");
  entries[3].arg_description = "SIGMAS";


  entries[4].long_name = "offset";
  entries[4].short_name = 'o';
  entries[4].flags = 0;
  entries[4].arg = G_OPTION_ARG_CALLBACK;
  entries[4].arg_data = parse_offset;
  entries[4].description
    = (
"\n     Image offset specification of the form \"a,b\" where a is \n"
"     counted in whole image pixels rightward and b downward from the top \n"
"     left corner of the first image argument.  The first occurence of this \n"
"     option specifies the offset of the top left corner of the second \n"
"     image, the second occurence the offset of the third image, etc. \n"
"     If any occurences of this option appear in an invocation, the correct \n"
"     number (i.e. one less than the number of images) must be supplied.\n");
  entries[4].arg_description = "SPEC";
  
  entries[5].long_name = "analysis-program";
  entries[5].short_name = 'a';
  entries[5].flags = 0;
  entries[5].arg = G_OPTION_ARG_STRING;
  entries[5].arg_data = &analysis_program;
  entries[5].description
    = (
"\n    Program to run when 'a' key is pressed.  The program is invoked \n"
"    with the following command line arguments:\n"
"\n"
"        tile_count            total number of image tiles to be passed\n"
"        base_name             image file base name\n"
"        tile_width            width of tile in pixels\n"
"        tile_height           height of tile in pixels\n"
"        tile_file_name        name of file containing tile data\n"
"\n"
"    where arguments 2 through 5 in the above list are repeated tile_count\n"
"    times.  The tile_width and tile_height arguments are generally equal to\n"
"    the value specified with the --analysis-tile-size option, but may be\n"
"    smaller (or even zero) if the cursor was near or off the edge of the\n"
"    image when analysis was requested.  The tile_file_name is the name of a\n"
"    file containing the tile data in big endian form.  It's probably\n"
"    easiest to use the float_image_new_from_file method with these\n"
"    arguments.  The base_name argument might be useful if metadata needs to\n"
"    be used or the analysis region needs to be grown algorithmicly.\n");
  entries[5].arg_description = "PROGRAM";

  entries[6].long_name = "async-analysis";
  entries[6].short_name = 0;
  entries[6].flags = 0;
  entries[6].arg = G_OPTION_ARG_NONE;
  entries[6].arg_data = &(self->async_analysis);
  entries[6].description
    = ( 
"\n    Run the analysis program asynchronously (i.e. in background,\n"
"    without waiting for it to complete.\n");
  entries[6].arg_description = "";   // Doesn't take an argument.

  entries[7].long_name = "analysis-tile-size";
  entries[7].short_name = 0;
  entries[7].flags = 0;
  entries[7].arg = G_OPTION_ARG_INT;
  entries[7].arg_data = &(self->analysis_tile_size);
  entries[7].description
    = (
"\n    Dimensions of (square) tiles to analyze (must be odd).  The default\n"
"    size is 51.\n");
  entries[7].arg_description = "TILE_SIZE";

  entries[8].long_name = G_OPTION_REMAINING;
  entries[8].short_name = 0;
  entries[8].flags = 0;
  entries[8].arg = G_OPTION_ARG_FILENAME_ARRAY;
  entries[8].arg_data = &image_names;
  entries[8].description = "YOU_HOPEFULLY_DONT_SEE_ME";
  entries[8].arg_description = "IMAGE_BASE_NAME [IMAGE_BASE_NAME...]";

  entries[9].long_name = NULL;

  GOptionGroup *ssv_group
    = g_option_group_new ("ssv", "ssv Options",
			  "Display help for ssv options.", self, NULL);
  
  g_option_group_add_entries (ssv_group, entries);

  GOptionContext *option_context = g_option_context_new ("");

  g_option_context_set_main_group (option_context, ssv_group);

  // Run the parser.
  GError *err = NULL;
  gboolean parse_results
    = g_option_context_parse (option_context, argc, argv, &err);
  if ( !parse_results ) {
    g_printerr ("%s: option parsing failed: %s\n", g_get_prgname (),
		err->message);
    exit (EXIT_FAILURE);
  }
  else {
    g_assert (err == NULL);
  }

  g_option_context_free (option_context);

  // Vet and copy the cache directory name (if provided) into a new
  // GString instance in self.
  if ( cache_dir != NULL ) {
    GError *err = NULL;
    my_is_writable_directory (cache_dir, &err);
    if ( err != NULL ) {
      g_printerr ("%s: bad -c or --cache-dir option argument '%s': %s\n",
		  g_get_prgname (), cache_dir, err->message);
      exit (EXIT_FAILURE);
    }
    g_string_free (self->cache_dir, TRUE);
    self->cache_dir = g_string_new (cache_dir);
  }

  g_free (cache_dir);

  // Vet and copy the analysis related arguments into their homes in
  // self.
  if ( analysis_program != NULL ) {
    self->analysis_program = g_string_new (analysis_program);
  }
  else {
    self->analysis_program = NULL;
  }
  if ( self->analysis_tile_size % 2 != 1 ) {
    g_printerr ("%s: bad --analysis_tile_size option argument '%d': not odd\n",
		g_get_prgname (), self->analysis_tile_size);
    exit (EXIT_FAILURE);
  }

  // Vet and copy the image name strings into GString instances in the
  // array in self.
  guint ii;
  for ( ii = 0 ; image_names != NULL && image_names[ii] != NULL ; ii++ ) {
    GString *cs = g_string_new (image_names[ii]);

    GError *err = NULL;

    GString *data_name = my_g_string_new_printf ("%s.img", cs->str);
    my_is_readable_file (data_name->str, &err);
    if ( err != NULL ) {
      g_printerr ("%s: file '%s' looks unreadable: %s\n",
		  g_get_prgname (), data_name->str, err->message);
      exit (EXIT_FAILURE);
    }
    my_g_string_free (data_name);

    GString *meta_name = my_g_string_new_printf ("%s.meta", cs->str);
    my_is_readable_file (meta_name->str, &err);
    if ( err != NULL ) {
      g_printerr ("%s: file '%s' looks unreadable: %s\n",
		  g_get_prgname (), meta_name->str, err->message);
      exit (EXIT_FAILURE);
    }
    my_g_string_free (meta_name);

    g_ptr_array_add (self->images, cs);
  }

  g_strfreev (image_names);

  // We require at least one image argument.
  if ( self->images->len < 1 ) {
    g_printerr ("%s: at least one image base name argument must be "
		"provided (try %s --help).\n", g_get_prgname (),
		g_get_prgname ());
    exit (EXIT_FAILURE);
  }

  // We require the corrent number of offset arguments.
  if ( self->x_offsets->len > 0 ) {
    if ( self->x_offsets->len != self->images->len - 1 ) {
      g_printerr ("%s: if any offset options are provided, the number "
		  "provided must be exactly one less than the number of image "
		  "arguments provided\n", g_get_prgname ());
      exit (EXIT_FAILURE);
    }
  }

  // IMPROVEME: Well this restriction has the potential to be very
  // annoying: if more than one image is specified to be loaded,
  // offset options must be specified for each image beyond the first.
  // The sensible thing would be to have default offset of (0, 0) or
  // course.  But it opend a small can or worms if we want and offset
  // for only the third image for example, and I just don't have the
  // time to go through and make everything agree.
  g_assert (self->x_offsets->len == self->images->len - 1);
  g_assert (self->x_offsets->len == self->y_offsets->len);

  self->reference_count = 1;

  return self;
}
Exemple #25
0
gboolean
mc_args_parse (int *argc, char ***argv, const char *translation_domain, GError ** mcerror)
{
    const gchar *_system_codepage;
    gboolean ok = TRUE;

    mc_return_val_if_error (mcerror, FALSE);

    _system_codepage = str_detect_termencoding ();

#ifdef ENABLE_NLS
    if (!str_isutf8 (_system_codepage))
        bind_textdomain_codeset ("mc", "UTF-8");
#endif

    context = g_option_context_new (mc_args_add_usage_info ());

    g_option_context_set_ignore_unknown_options (context, FALSE);

    mc_args_add_extended_info_to_help ();

    main_group = g_option_group_new ("main", _("Main options"), _("Main options"), NULL, NULL);

    g_option_group_add_entries (main_group, argument_main_table);
    g_option_context_set_main_group (context, main_group);
    g_option_group_set_translation_domain (main_group, translation_domain);

    terminal_group = g_option_group_new ("terminal", _("Terminal options"),
                                         _("Terminal options"), NULL, NULL);

    g_option_group_add_entries (terminal_group, argument_terminal_table);
    g_option_context_add_group (context, terminal_group);
    g_option_group_set_translation_domain (terminal_group, translation_domain);

    color_group = mc_args_new_color_group ();

    g_option_group_add_entries (color_group, argument_color_table);
    g_option_context_add_group (context, color_group);
    g_option_group_set_translation_domain (color_group, translation_domain);

    if (!g_option_context_parse (context, argc, argv, mcerror))
    {
        if (*mcerror == NULL)
            mc_propagate_error (mcerror, 0, "%s\n", _("Arguments parse error!"));
        else
        {
            gchar *help_str;

            help_str = g_option_context_get_help (context, TRUE, NULL);

            if (str_isutf8 (_system_codepage))
                mc_replace_error (mcerror, (*mcerror)->code, "%s\n\n%s\n", (*mcerror)->message,
                                  help_str);
            else
            {
                gchar *full_help_str;

                full_help_str =
                    mc_args__convert_help_to_syscharset (_system_codepage, (*mcerror)->message,
                                                         help_str);
                mc_replace_error (mcerror, (*mcerror)->code, "%s", full_help_str);
                g_free (full_help_str);
            }
            g_free (help_str);
        }

        ok = FALSE;
    }

    g_option_context_free (context);
    mc_args_clean_temp_help_strings ();

#ifdef ENABLE_NLS
    if (!str_isutf8 (_system_codepage))
        bind_textdomain_codeset ("mc", _system_codepage);
#endif

    return ok;
}
Exemple #26
0
gint
main (gint argc, gchar ** argv)
{
  gboolean res = FALSE;
  gboolean arg_version = FALSE;
  gboolean arg_quiet = FALSE;
  gchar *command = NULL, *input_file_name = NULL, *output_file_name = NULL;
  gint saved_argc = argc;
  BtCmdApplication *app;
  GOptionContext *ctx;
  GOptionGroup *group;
  GError *err = NULL;

#ifdef ENABLE_NLS
  setlocale (LC_ALL, "");
  bindtextdomain (GETTEXT_PACKAGE, LOCALEDIR);
  bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
  textdomain (GETTEXT_PACKAGE);
#endif /* ENABLE_NLS */

  static GOptionEntry options[] = {
    {"version", '\0', 0, G_OPTION_ARG_NONE, NULL,
        N_("Print application version"), NULL},
    {"quiet", 'q', 0, G_OPTION_ARG_NONE, NULL, N_("Be quiet"), NULL},
    {"command", 'c', 0, G_OPTION_ARG_STRING, NULL, N_("Command name"),
        "{info, play, convert, encode}"},
    {"input-file", 'i', 0, G_OPTION_ARG_FILENAME, NULL, N_("Input file name"),
        N_("<songfile>")},
    {"output-file", 'o', 0, G_OPTION_ARG_FILENAME, NULL, N_("Output file name"),
        N_("<songfile>")},
    {NULL}
  };
  // setting this separately gets us from 76 to 10 instructions
  options[0].arg_data = &arg_version;
  options[1].arg_data = &arg_quiet;
  options[2].arg_data = &command;
  options[3].arg_data = &input_file_name;
  options[4].arg_data = &output_file_name;

  // init libraries
  ctx = g_option_context_new (NULL);
  //g_option_context_add_main_entries(ctx, options, GETTEXT_PACKAGE);
  group =
      g_option_group_new ("main", _("buzztrax-cmd options"),
      _("Show buzztrax-cmd options"), argv[0], NULL);
  g_option_group_add_entries (group, options);
  g_option_group_set_translation_domain (group, GETTEXT_PACKAGE);
  g_option_context_set_main_group (ctx, group);

  bt_init_add_option_groups (ctx);
  g_option_context_add_group (ctx, btic_init_get_option_group ());

  if (!g_option_context_parse (ctx, &argc, &argv, &err)) {
    g_print ("Error initializing: %s\n", safe_string (err->message));
    g_option_context_free (ctx);
    exit (1);
  }
  if (arg_version) {
    g_printf ("%s from " PACKAGE_STRING "\n", argv[0]);
    res = TRUE;
    goto Done;
  }
  if (!command) {
    if (argc == saved_argc) {
      usage (argc, argv, ctx);
    }
    goto Done;
  }

  GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, "bt-cmd", 0,
      "music production environment / command ui");
  GST_INFO ("starting: command=\"%s\" input=\"%s\" output=\"%s\"", command,
      input_file_name, output_file_name);

  // give some global context info
  g_set_prgname ("buzztrax-cmd");
  g_set_application_name ("Buzztrax");
  g_setenv ("PULSE_PROP_application.icon_name", "buzztrax", TRUE);
  g_setenv ("PULSE_PROP_media.role", "production", TRUE);

  app = bt_cmd_application_new (arg_quiet);


  // set a default command, if a file is given
  if (!command && BT_IS_STRING (input_file_name)) {
    command = g_strdup ("p");
  }
  // depending on the options call the correct method
  if (!strcmp (command, "p") || !strcmp (command, "play")) {
    if (!BT_IS_STRING (input_file_name))
      usage (argc, argv, ctx);
    res = bt_cmd_application_play (app, input_file_name);
  } else if (!strcmp (command, "i") || !strcmp (command, "info")) {
    if (!BT_IS_STRING (input_file_name))
      usage (argc, argv, ctx);
    res = bt_cmd_application_info (app, input_file_name, output_file_name);
  } else if (!strcmp (command, "c") || !strcmp (command, "convert")) {
    if (!BT_IS_STRING (input_file_name) || !BT_IS_STRING (output_file_name))
      usage (argc, argv, ctx);
    res = bt_cmd_application_convert (app, input_file_name, output_file_name);
  } else if (!strcmp (command, "e") || !strcmp (command, "encode")) {
    if (!BT_IS_STRING (input_file_name) || !BT_IS_STRING (output_file_name))
      usage (argc, argv, ctx);
    res = bt_cmd_application_encode (app, input_file_name, output_file_name);
  } else
    usage (argc, argv, ctx);

  // free application
  g_object_unref (app);

Done:
  g_free (command);
  g_free (input_file_name);
  g_free (output_file_name);
  g_option_context_free (ctx);

  return !res;
}
Exemple #27
0
Configuration* configuration_new(gint argc, gchar* argv[]) {
	/* get memory */
	Configuration* c = g_new0(Configuration, 1);
	MAGIC_INIT(c);

	c->argstr = g_strjoinv(" ", argv);

	const gchar* required_parameters = "shadow.config.xml";
	gint nRequiredXMLFiles = 1;

	c->context = g_option_context_new(required_parameters);
	g_option_context_set_summary(c->context, "Shadow - run real applications over simulated networks");
	g_option_context_set_description(c->context,
		"Shadow is a unique discrete-event network simulator that runs real "
		"applications like Tor, and distributed systems of thousands of nodes "
		"on a single machine. Shadow combines the accuracy of emulation with the "
		"efficiency and control of simulation, achieving the best of both approaches.");

	/* set defaults */
	c->initialTCPWindow = 10;
	c->interfaceBufferSize = 1024000;
	c->interfaceBatchTime = 10;
	c->randomSeed = 1;
	c->cpuThreshold = -1;
	c->cpuPrecision = 200;
	c->heartbeatInterval = 60;

	/* set options to change defaults for the main group */
	c->mainOptionGroup = g_option_group_new("main", "Main Options", "Primary simulator options", NULL, NULL);
	const GOptionEntry mainEntries[] = {
      { "debug", 'd', 0, G_OPTION_ARG_NONE, &(c->debug), "Pause at startup for debugger attachment", NULL },
	  { "heartbeat-frequency", 'h', 0, G_OPTION_ARG_INT, &(c->heartbeatInterval), "Log node statistics every N seconds [60]", "N" },
	  { "heartbeat-log-level", 'j', 0, G_OPTION_ARG_STRING, &(c->heartbeatLogLevelInput), "Log LEVEL at which to print node statistics ['message']", "LEVEL" },
	  { "heartbeat-log-info", 'i', 0, G_OPTION_ARG_STRING, &(c->heartbeatLogInfo), "Comma separated list of information contained in heartbeat ('node','socket','ram') ['node']", "LIST"},
	  { "log-level", 'l', 0, G_OPTION_ARG_STRING, &(c->logLevelInput), "Log LEVEL above which to filter messages ('error' < 'critical' < 'warning' < 'message' < 'info' < 'debug') ['message']", "LEVEL" },
	  { "preload", 'p', 0, G_OPTION_ARG_STRING, &(c->preloads), "LD_PRELOAD environment VALUE to use for function interposition (/path/to/lib:...) [None]", "VALUE" },
	  { "runahead", 'r', 0, G_OPTION_ARG_INT, &(c->minRunAhead), "If set, overrides the automatically calculated minimum TIME workers may run ahead when sending events between nodes, in milliseconds [0]", "TIME" },
	  { "seed", 's', 0, G_OPTION_ARG_INT, &(c->randomSeed), "Initialize randomness for each thread using seed N [1]", "N" },
	  { "workers", 'w', 0, G_OPTION_ARG_INT, &(c->nWorkerThreads), "Run concurrently with N worker threads [0]", "N" },
	  { "valgrind", 'x', 0, G_OPTION_ARG_NONE, &(c->runValgrind), "Run through valgrind for debugging", NULL },
	  { "version", 'v', 0, G_OPTION_ARG_NONE, &(c->printSoftwareVersion), "Print software version and exit", NULL },
	  { NULL },
	};

	g_option_group_add_entries(c->mainOptionGroup, mainEntries);
	g_option_context_set_main_group(c->context, c->mainOptionGroup);

    /* now fill in the default plug-in examples option group */
    c->pluginsOptionGroup = g_option_group_new("sim", "Simulation Examples", "Built-in simulation examples", NULL, NULL);
    const GOptionEntry pluginEntries[] =
    {
      { "file", 0, 0, G_OPTION_ARG_NONE, &(c->runFileExample), "Run basic HTTP file transfer simulation", NULL },
      { NULL },
    };

    g_option_group_add_entries(c->pluginsOptionGroup, pluginEntries);
    g_option_context_add_group(c->context, c->pluginsOptionGroup);

	/* now fill in the network option group */
	GString* sockrecv = g_string_new("");
	g_string_printf(sockrecv, "Initialize the socket receive buffer to N bytes [%i]", (gint)CONFIG_RECV_BUFFER_SIZE);
	GString* socksend = g_string_new("");
	g_string_printf(socksend, "Initialize the socket send buffer to N bytes [%i]", (gint)CONFIG_SEND_BUFFER_SIZE);

	c->networkOptionGroup = g_option_group_new("sys", "System Options", "Simulated system/network behavior", NULL, NULL);
	const GOptionEntry networkEntries[] =
	{
	  { "cpu-precision", 0, 0, G_OPTION_ARG_INT, &(c->cpuPrecision), "round measured CPU delays to the nearest TIME, in microseconds (negative value to disable fuzzy CPU delays) [200]", "TIME" },
	  { "cpu-threshold", 0, 0, G_OPTION_ARG_INT, &(c->cpuThreshold), "TIME delay threshold after which the CPU becomes blocked, in microseconds (negative value to disable CPU delays) (experimental!) [-1]", "TIME" },
	  { "interface-batch", 0, 0, G_OPTION_ARG_INT, &(c->interfaceBatchTime), "Batch TIME for network interface sends and receives, in milliseconds [10]", "TIME" },
	  { "interface-buffer", 0, 0, G_OPTION_ARG_INT, &(c->interfaceBufferSize), "Size of the network interface receive buffer, in bytes [1024000]", "N" },
	  { "interface-qdisc", 0, 0, G_OPTION_ARG_STRING, &(c->interfaceQueuingDiscipline), "The interface queuing discipline QDISC used to select the next sendable socket ('fifo' or 'rr') ['fifo']", "QDISC" },
	  { "socket-recv-buffer", 0, 0, G_OPTION_ARG_INT, &(c->initialSocketReceiveBufferSize), sockrecv->str, "N" },
	  { "socket-send-buffer", 0, 0, G_OPTION_ARG_INT, &(c->initialSocketSendBufferSize), socksend->str, "N" },
	  { "tcp-congestion-control", 0, 0, G_OPTION_ARG_STRING, &(c->tcpCongestionControl), "Congestion control algorithm to use for TCP ('aimd', 'reno', 'cubic') ['cubic']", "TCPCC" },
	  { "tcp-ssthresh", 0, 0, G_OPTION_ARG_INT, &(c->tcpSlowStartThreshold), "Set TCP ssthresh value instead of discovering it via packet loss or hystart [0]", "N" },
	  { "tcp-windows", 0, 0, G_OPTION_ARG_INT, &(c->initialTCPWindow), "Initialize the TCP send, receive, and congestion windows to N packets [10]", "N" },
	  { NULL },
	};

	g_option_group_add_entries(c->networkOptionGroup, networkEntries);
	g_option_context_add_group(c->context, c->networkOptionGroup);

	/* parse args */
	GError *error = NULL;
	if (!g_option_context_parse(c->context, &argc, &argv, &error)) {
		g_printerr("** %s **\n", error->message);
		gchar* helpString = g_option_context_get_help(c->context, TRUE, NULL);
		g_printerr("%s", helpString);
		g_free(helpString);
		configuration_free(c);
		return NULL;
	}

	/* make sure we have the required arguments. program name is first arg.
	 * printing the software version requires no other args. running a
	 * plug-in example also requires no other args. */
	if(!(c->printSoftwareVersion) && !(c->runFileExample) && (argc < nRequiredXMLFiles + 1)) {
		g_printerr("** Please provide the required parameters **\n");
		gchar* helpString = g_option_context_get_help(c->context, TRUE, NULL);
		g_printerr("%s", helpString);
		g_free(helpString);
		configuration_free(c);
		return NULL;
	}

	if(c->nWorkerThreads < 0) {
		c->nWorkerThreads = 0;
	}
	if(c->logLevelInput == NULL) {
		c->logLevelInput = g_strdup("message");
	}
	if(c->heartbeatLogLevelInput == NULL) {
		c->heartbeatLogLevelInput = g_strdup("message");
	}
	if(c->heartbeatLogInfo == NULL) {
		c->heartbeatLogInfo = g_strdup("node");
	}
	if(c->heartbeatInterval < 1) {
		c->heartbeatInterval = 1;
	}
	if(c->initialTCPWindow < 1) {
		c->initialTCPWindow = 1;
	}
	if(c->interfaceBufferSize < CONFIG_MTU) {
		c->interfaceBufferSize = CONFIG_MTU;
	}
	c->interfaceBatchTime *= SIMTIME_ONE_MILLISECOND;
	if(c->interfaceBatchTime == 0) {
		/* we require at least 1 nanosecond b/c of time granularity */
		c->interfaceBatchTime = 1;
	}
	if(c->interfaceQueuingDiscipline == NULL) {
		c->interfaceQueuingDiscipline = g_strdup("fifo");
	}
	if(!c->initialSocketReceiveBufferSize) {
		c->initialSocketReceiveBufferSize = CONFIG_RECV_BUFFER_SIZE;
		c->autotuneSocketReceiveBuffer = TRUE;
	}
	if(!c->initialSocketSendBufferSize) {
		c->initialSocketSendBufferSize = CONFIG_SEND_BUFFER_SIZE;
		c->autotuneSocketSendBuffer = TRUE;
	}
	if(c->tcpCongestionControl == NULL) {
		c->tcpCongestionControl = g_strdup("cubic");
	}

	c->inputXMLFilenames = g_queue_new();
	for(gint i = 1; i < argc; i++) {
		GString* filename = g_string_new(argv[i]);
		g_queue_push_tail(c->inputXMLFilenames, filename);
	}

	if(socksend) {
		g_string_free(socksend, TRUE);
	}
	if(sockrecv) {
		g_string_free(sockrecv, TRUE);
	}

	return c;
}
Exemple #28
0
int
main(int argc, char *argv[])
{
    gboolean print_version = FALSE;
    gboolean one_shot = FALSE;
    gchar *output_plugin = NULL;
    gchar **servers_desc = NULL;
    gchar **streams_desc = NULL;
    gchar **input_plugins = NULL;
    gchar **order = NULL;
    gchar *config = NULL;

    int retval = 0;
    GError *error = NULL;
    GOptionContext *option_context = NULL;
    GOptionGroup *option_group;

#if DEBUG
    g_setenv("G_MESSAGES_DEBUG", "all", FALSE);
#endif /* ! DEBUG */

    setlocale(LC_ALL, "");
#ifdef ENABLE_NLS
    bindtextdomain(GETTEXT_PACKAGE, LOCALEDIR);
    bind_textdomain_codeset(GETTEXT_PACKAGE, "UTF-8");
#endif /* ENABLE_NLS */

#if DEBUG
    const gchar *debug_log_filename =  g_getenv("J4STATUS_DEBUG_LOG_FILENAME");
    GDataOutputStream *debug_stream = NULL;

    if ( debug_log_filename != NULL )
    {
        GFile *debug_log;

        debug_log = g_file_new_for_path(debug_log_filename);

        GError *error = NULL;
        GFileOutputStream *debug_log_stream;

        debug_log_stream = g_file_append_to(debug_log, G_FILE_CREATE_NONE, NULL, &error);

        if ( debug_log_stream == NULL )
        {
            g_warning("Couldn't open debug log file: %s", error->message);
            g_clear_error(&error);
        }
        else
        {
            debug_stream = g_data_output_stream_new(G_OUTPUT_STREAM(debug_log_stream));
            g_object_unref(debug_log_stream);

            g_log_set_default_handler(_j4status_core_debug_log_handler, debug_stream);
        }
        g_object_unref(debug_log);
    }
#endif /* DEBUG */

    GOptionEntry entries[] =
    {
        { "output",     'o', 0, G_OPTION_ARG_STRING,       &output_plugin, "Output plugin to use", "<plugin>" },
        { "listen",     'l', 0, G_OPTION_ARG_STRING_ARRAY, &servers_desc,  "Socket to listen on, will create a stream on connection (may be specified several times)", "<listen description>" },
        { "stream",     't', 0, G_OPTION_ARG_STRING_ARRAY, &streams_desc,  "Stream to read from/write to (may be specified several times)", "<stream description>" },
        { "input",      'i', 0, G_OPTION_ARG_STRING_ARRAY, &input_plugins, "Input plugins to use (may be specified several times)", "<plugin>" },
        { "order",      'O', 0, G_OPTION_ARG_STRING_ARRAY, &order,         "Order of sections, specified once a section (see man)", "<section id>" },
        { "one-shot",   '1', 0, G_OPTION_ARG_NONE,         &one_shot,      "Tells j4status to stop right after starting",           NULL },
        { "config",     'c', 0, G_OPTION_ARG_STRING,       &config,        "Config file to use", "<config>" },
        { "version",    'V', 0, G_OPTION_ARG_NONE,         &print_version, "Print version",        NULL },
        { NULL }
    };


    option_context = g_option_context_new("- status line generator");

    option_group = g_option_group_new(NULL, NULL, NULL, NULL, NULL);
    g_option_group_set_translation_domain(option_group, GETTEXT_PACKAGE);
    g_option_group_add_entries(option_group, entries);
    g_option_context_set_main_group(option_context, option_group);

    if ( ! g_option_context_parse(option_context, &argc, &argv, &error) )
    {
        g_warning("Option parsing failed: %s\n", error->message);
        g_clear_error(&error);
        retval = 1;
        goto end;
    }
    g_option_context_free(option_context);

    if ( print_version )
    {
        g_fprintf(stdout, PACKAGE_NAME " " PACKAGE_VERSION "\n");
        goto end;
    }

    if ( config != NULL )
    {
        g_setenv("J4STATUS_CONFIG_FILE", config, TRUE);
        g_free(config);
    }

    GKeyFile *key_file;
    key_file = j4status_config_get_key_file("Plugins");
    if ( key_file != NULL )
    {
        if ( output_plugin == NULL )
            output_plugin = g_key_file_get_string(key_file, "Plugins", "Output", NULL);

        if ( input_plugins == NULL )
            input_plugins = g_key_file_get_string_list(key_file, "Plugins", "Input", NULL, NULL);

        if ( order == NULL )
            order = g_key_file_get_string_list(key_file, "Plugins", "Order", NULL, NULL);

        g_key_file_free(key_file);
    }

    J4statusCoreContext *context;
    context = g_new0(J4statusCoreContext, 1);

    J4statusCoreInterface interface = {
        .context = context,
        .add_section = _j4status_core_add_section,
        .remove_section = _j4status_core_remove_section,
        .trigger_generate = _j4status_core_trigger_generate,
        .trigger_action = _j4status_core_trigger_action,
    };

#ifdef G_OS_UNIX
    g_unix_signal_add(SIGTERM, _j4status_core_source_quit, context);

    g_unix_signal_add(SIGINT, _j4status_core_source_quit, context);
    g_unix_signal_add(SIGUSR1, _j4status_core_signal_usr1, context);
    g_unix_signal_add(SIGUSR2, _j4status_core_signal_usr2, context);

    /* Ignore SIGPIPE as it is useless */
    signal(SIGPIPE, SIG_IGN);
#endif /* G_OS_UNIX */

    context->output_plugin = j4status_plugins_get_output_plugin(&interface, output_plugin);
    if ( context->output_plugin == NULL )
    {
        g_warning("No usable output plugin, tried '%s'", output_plugin);
        retval = 10;
        goto end;
    }

    gchar *header = NULL;
    if ( context->output_plugin->interface.generate_header != NULL )
        header = context->output_plugin->interface.generate_header(context->output_plugin->context);

    /* Creating input/output stream */
    context->io = j4status_io_new(context, header, (const gchar * const *) servers_desc, (const gchar * const *) streams_desc);
    if ( context->io == NULL )
    {
        g_warning("Couldn't create input/output streams");
        retval = 2;
        goto end;
    }

    if ( order != NULL )
    {
        context->order_weights = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, NULL);
        gchar **id;
        for ( id = order ; *id != NULL ; ++id )
            g_hash_table_insert(context->order_weights, *id, GINT_TO_POINTER(1 + id - order));
        g_free(order);
    }

    context->sections_hash = g_hash_table_new(g_str_hash, g_str_equal);

    context->input_plugins = j4status_plugins_get_input_plugins(&interface, input_plugins);
    if ( context->input_plugins == NULL )
    {
        g_warning("No input plugins, will stop early");
        one_shot = TRUE;
        retval = 11;
    }
    context->sections = g_list_reverse(context->sections);
    if ( context->order_weights != NULL )
        context->sections = g_list_sort(context->sections, _j4status_core_compare_sections);

    _j4status_core_start(context);

    if ( one_shot )
        g_idle_add(_j4status_core_source_quit, context);

    context->loop = g_main_loop_new(NULL, FALSE);
    g_main_loop_run(context->loop);
    g_main_loop_unref(context->loop);
    context->loop = NULL;

    GList *input_plugin_;
    J4statusInputPlugin *input_plugin;
    for ( input_plugin_ = context->input_plugins ; input_plugin_ != NULL ; input_plugin_ = g_list_next(input_plugin_) )
    {
        input_plugin = input_plugin_->data;
        input_plugin->interface.uninit(input_plugin->context);
    }

    if ( context->output_plugin->interface.uninit != NULL )
        context->output_plugin->interface.uninit(context->output_plugin->context);

    j4status_io_free(context->io);

    if ( context->order_weights != NULL )
        g_hash_table_unref(context->order_weights);

    g_hash_table_unref(context->sections_hash);

end:
#if DEBUG
    if ( debug_stream != NULL )
        g_object_unref(debug_stream);
#endif /* DEBUG */

    return retval;
}
Exemple #29
0
int main(int argc, char *argv[]) {
	struct configuration conf= { NULL, NULL, NULL, 0 };

	GError *error= NULL;
	GOptionContext *context;

	g_thread_init(NULL);

	init_mutex= g_mutex_new();

	context= g_option_context_new("multi-threaded MySQL loader");
	GOptionGroup *main_group= g_option_group_new("main", "Main Options", "Main Options", NULL, NULL);
	g_option_group_add_entries(main_group, entries);
	g_option_group_add_entries(main_group, common_entries);
	g_option_context_set_main_group(context, main_group);
	if (!g_option_context_parse(context, &argc, &argv, &error)) {
		g_print("option parsing failed: %s, try --help\n", error->message);
		exit(EXIT_FAILURE);
	}
	g_option_context_free(context);

	if (program_version) {
		g_print("myloader %s, built against MySQL %s\n", VERSION, MYSQL_SERVER_VERSION);
		exit(EXIT_SUCCESS);
	}

	set_verbose(verbose);

	if (!directory) {
		g_critical("a directory needs to be specified, see --help\n");
		exit(EXIT_FAILURE);
	} else {
		char *p= g_strdup_printf("%s/metadata", directory);
		if (!g_file_test(p, G_FILE_TEST_EXISTS)) {
			g_critical("the specified directory is not a mydumper backup\n");
			exit(EXIT_FAILURE);
		}
	}

	MYSQL *conn;
	conn= mysql_init(NULL);
	mysql_options(conn, MYSQL_READ_DEFAULT_GROUP, "myloader");

	if (!mysql_real_connect(conn, hostname, username, password, NULL, port, socket_path, 0)) {
		g_critical("Error connection to database: %s", mysql_error(conn));
		exit(EXIT_FAILURE);
	}
	if (!enable_binlog)
		mysql_query(conn, "SET SQL_LOG_BIN=0");

	mysql_query(conn, "/*!40014 SET FOREIGN_KEY_CHECKS=0*/");
	conf.queue= g_async_queue_new();
	conf.ready= g_async_queue_new();

	guint n;
	GThread **threads= g_new(GThread*, num_threads);
	struct thread_data *td= g_new(struct thread_data, num_threads);
	for (n= 0; n < num_threads; n++) {
		td[n].conf= &conf;
		td[n].thread_id= n+1;
		threads[n]= g_thread_create((GThreadFunc)process_queue, &td[n], TRUE, NULL);
		g_async_queue_pop(conf.ready);
	}
	g_async_queue_unref(conf.ready);

	g_message("%d threads created", num_threads);

        restore_databases(&conf, conn);

	for (n= 0; n < num_threads; n++) {
		struct job *j= g_new0(struct job, 1);
		j->type = JOB_SHUTDOWN;
		g_async_queue_push(conf.queue, j);
	}

	for (n= 0; n < num_threads; n++) {
		g_thread_join(threads[n]);
	}

	g_async_queue_unref(conf.queue);
	mysql_close(conn);
	mysql_thread_end();
	mysql_library_end();
	g_free(directory);
	g_free(td);
	g_free(threads);

	return errors ? EXIT_FAILURE : EXIT_SUCCESS;
}
Exemple #30
0
int
main( int argc, char **argv )
{
	GOptionContext *context;
	GOptionGroup *main_group;
	GError *error = NULL;
	int i;
	int result;

	if( VIPS_INIT( argv[0] ) )
	        vips_error_exit( "unable to start VIPS" );
	textdomain( GETTEXT_PACKAGE );
	setlocale( LC_ALL, "" );

        context = g_option_context_new( _( "- thumbnail generator" ) );

	main_group = g_option_group_new( NULL, NULL, NULL, NULL, NULL );
	g_option_group_add_entries( main_group, options );
	vips_add_option_entries( main_group ); 
	g_option_group_set_translation_domain( main_group, GETTEXT_PACKAGE );
	g_option_context_set_main_group( context, main_group );

	if( !g_option_context_parse( context, &argc, &argv, &error ) ) {
		if( error ) {
			fprintf( stderr, "%s\n", error->message );
			g_error_free( error );
		}

		vips_error_exit( "try \"%s --help\"", g_get_prgname() );
	}

	g_option_context_free( context );

	if( sscanf( thumbnail_size, "%d x %d", 
		&thumbnail_width, &thumbnail_height ) != 2 ) {
		if( sscanf( thumbnail_size, "%d", &thumbnail_width ) != 1 ) 
			vips_error_exit( "unable to parse size \"%s\" -- "
				"use eg. 128 or 200x300", thumbnail_size );

		thumbnail_height = thumbnail_width;
	}

	if( rotate_image ) {
#ifndef HAVE_EXIF
		vips_warn( "vipsthumbnail", "%s",
			_( "auto-rotate disabled: "
			      "libvips built without exif support" ) );
#endif /*!HAVE_EXIF*/
	}

	result = 0;

	for( i = 1; i < argc; i++ ) {
		/* Hang resources for processing this thumbnail off @process.
		 */
		VipsObject *process = VIPS_OBJECT( vips_image_new() ); 

		if( thumbnail_process( process, argv[i] ) ) {
			fprintf( stderr, "%s: unable to thumbnail %s\n", 
				argv[0], argv[i] );
			fprintf( stderr, "%s", vips_error_buffer() );
			vips_error_clear();

			/* We had a conversion failure: return an error code
			 * when we finally exit.
			 */
			result = -1;
		}

		g_object_unref( process );
	}

	vips_shutdown();

	return( result );
}