Ejemplo n.º 1
0
static void _save_file(EDITOR *e)
{
	GtkRecentManager *rm = NULL;
	GString *data = g_string_new("");

	editor_get_document_content(data, e);
	XI_message(("%s", data->str));

	if (!e->filename || (0 == g_strcmp0("Untitled document", e->filename)) || g_strrstr(e->filename, ".spt")) {
		GtkWidget *dialog = gtk_file_chooser_dialog_new("Save as",		      //const gchar *title,
								NULL,			      //GtkWindow *parent,
								GTK_FILE_CHOOSER_ACTION_SAVE, //GtkFileChooserAction action,
#ifdef HAVE_GTK_310
								"_OK",
								GTK_RESPONSE_OK,
								"_Cancel",
								GTK_RESPONSE_CANCEL,
#else
								GTK_STOCK_OK,
								GTK_RESPONSE_OK,
								GTK_STOCK_CANCEL,
								GTK_RESPONSE_CANCEL,
#endif
								NULL);
		gtk_file_chooser_set_do_overwrite_confirmation(GTK_FILE_CHOOSER(dialog), TRUE);

		gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(dialog),
						    settings.studypaddir);
		if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_OK) {
			gchar *filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog));
			e->filename = g_strdup(filename);
			GFile *gfile = g_file_parse_name(filename);
			g_file_replace_contents(gfile, data->str, data->len, NULL, TRUE, G_FILE_CREATE_NONE, NULL, NULL, NULL); //GError **error
		}
		change_window_title(e->window, e->filename);
		gtk_widget_destroy(dialog);

	} else {

		GFile *gfile = g_file_parse_name(e->filename);
		g_file_replace_contents(gfile, data->str, data->len, NULL, TRUE, G_FILE_CREATE_NONE, NULL, NULL, NULL); //GError **error
	}

	rm = gtk_recent_manager_get_default();
	gtk_recent_manager_add_item(rm, e->filename);

	e->is_changed = FALSE;
	g_string_free(data, TRUE);
}
Ejemplo n.º 2
0
static void _configfile (CustomData *data, gboolean writemode) {
    gchar *filename = g_strdup_printf("file://%s/.4deckradio", g_get_home_dir());
    g_print ("config file: %s\n", filename);
    GFile *file = g_file_new_for_uri (filename);

    if (TRUE == writemode) {
        /* Save the last folder locations to ~/.4deckradio */
        GString *configstring = g_string_new("");
        for (int i=0; i < NUM_PLAYERS; i++) {
            g_print ("deck %i folder %s\n", i, data[i].last_folder_uri);
            g_string_append_printf (configstring, "%s\n", data[i].last_folder_uri);
        }

        g_file_replace_contents (file,
                configstring->str,
                configstring->len,
                NULL, /* old etag */
                FALSE, /* backup */
                G_FILE_CREATE_PRIVATE,
                NULL, /* new etag */
                NULL, /* cancellable */
                NULL);
        g_string_free (configstring, TRUE);
    } else {
        /* load config file */
        GFileInputStream *inputstream = g_file_read (file,
                NULL,
                NULL);
        if (NULL == inputstream) {
            return;
        }

        GDataInputStream *config = g_data_input_stream_new (G_INPUT_STREAM (inputstream));

        if (NULL == config) {
            return;
        }


        GError *error = NULL;

        for (int i = 0; i < NUM_PLAYERS; i++) {
            gsize length;
            data[i].last_folder_uri =
                g_data_input_stream_read_line_utf8(config, &length, NULL, &error);
            if (NULL != error) {
                g_print ("Error reading config file: %s\n", error->message);
            }
            g_clear_error (&error);
            g_print ("Will use %s for deck %i\n", data[i].last_folder_uri, i);
        }

        g_input_stream_close (G_INPUT_STREAM (config), NULL, NULL);
        g_input_stream_close (G_INPUT_STREAM (inputstream), NULL, NULL);
        g_object_unref (config);
        g_object_unref (inputstream);
    }
    g_free (filename);
    g_object_unref (file);
}
Ejemplo n.º 3
0
static gboolean
_g_key_file_save_to_uri (GKeyFile *key_file,
                         const char *uri,
                         GError  **error)
{
    GFile *file;
    char *data;
    gsize len;

    data = g_key_file_to_data (key_file, &len, error);
    if (data == NULL)
    {
        return FALSE;
    }
    file = g_file_new_for_uri (uri);
    if (!g_file_replace_contents (file,
                                  data, len,
                                  NULL, FALSE,
                                  G_FILE_CREATE_NONE,
                                  NULL, NULL, error))
    {
        g_object_unref (file);
        g_free (data);
        return FALSE;
    }
    g_object_unref (file);
    g_free (data);
    return TRUE;
}
Ejemplo n.º 4
0
bool MetadataManager::save(MetadataManager* manager)
{
	XOJ_CHECK_TYPE_OBJ(manager, MetadataManager);

	manager->timeoutId = 0;

	manager->cleanupMetadata();

	gsize length = 0;
	char* data = g_key_file_to_data(manager->config, &length, NULL);
	char* fileName = FILENAME();
	GFile* file = g_file_new_for_path(fileName);

	if (!g_file_replace_contents(file, data, length, NULL, false,
	                             G_FILE_CREATE_PRIVATE, NULL, NULL, NULL))
	{
		g_warning("could not write metadata file: %s", fileName);
	}

	g_free(data);
	g_free(fileName);
	g_object_unref(file);

	return false;
}
Ejemplo n.º 5
0
static gboolean
download_archive (SoupURI      *uri,
                  const gchar  *sha,
                  GFile        *archive_file,
                  GError      **error)
{
  g_autoptr(GBytes) content = NULL;
  g_autofree gchar *sha256 = NULL;

  content = download_uri (uri, error);
  if (content == NULL)
    return FALSE;

  sha256 = g_compute_checksum_for_bytes (G_CHECKSUM_SHA256, content);
  if (g_strcmp0 (sha256, sha) != 0)
    {
      g_autofree gchar *path = g_file_get_path (archive_file);
      g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                   "Wrong sha256 for %s, expected %s, was %s",
                   path, sha, sha256);
      return FALSE;
    }

  return g_file_replace_contents (archive_file,
                                  g_bytes_get_data (content, NULL),
                                  g_bytes_get_size (content),
                                  NULL, FALSE, G_FILE_CREATE_NONE, NULL,
                                  NULL, error);
}
Ejemplo n.º 6
0
int gtodo_client_save_xml_to_file(GTodoClient *cl, GFile *file, GError **error)
{
	xmlChar *buffer;
	GError *tmp_error = NULL;
	int size;

	/* Test if there is actually a client to save */
	if(cl == NULL)
	{
		g_set_error(&tmp_error,LIBGTODO_ERROR,LIBGTODO_ERROR_GENERIC,_("No Gtodo Client to save.") );
		g_propagate_error(error, tmp_error);
		return TRUE;
	}
	/* dump the xml to memory */
	/* xmlIndentTreeOutput = 1; */
	xmlKeepBlanksDefault(0);
	xmlDocDumpFormatMemory(cl->gtodo_doc, &buffer, &size, TRUE);

	if (!g_file_replace_contents (file, 
			(char *)buffer, size, 
			NULL, FALSE, G_FILE_CREATE_NONE, 
			NULL, NULL, &tmp_error))
	{
		g_propagate_error(error, tmp_error);
		xmlFree(buffer);
		return TRUE;
	}

	xmlFree(buffer);
	/* return that everything is ok */
	return FALSE;
}
Ejemplo n.º 7
0
/**
 * pk_package_sack_add_packages_from_file:
 * @sack: a valid #PkPackageSack instance
 * @file: a valid package-list file
 * @error: a %GError to put the error code and message in, or %NULL
 *
 * Write the contents of a PkPackageSack to a package-list file.
 *
 * Return value: %TRUE if there were no errors.
 *
 * Since: 0.8.6
 **/
gboolean
pk_package_sack_to_file (PkPackageSack *sack, GFile *file, GError **error)
{
	gboolean ret;
	GString *string;
	guint i;
	PkPackage *pkg;

	string = g_string_new ("");
	for (i = 0; i < sack->priv->array->len; i++) {
		pkg = g_ptr_array_index (sack->priv->array, i);
		g_string_append_printf (string,
					"%s\t%s\t%s\n",
					pk_info_enum_to_string (pk_package_get_info (pkg)),
					pk_package_get_id (pkg),
					pk_package_get_summary (pkg));
	}
	ret = g_file_replace_contents (file,
				       string->str,
				       string->len,
				       NULL,
				       FALSE,
				       G_FILE_CREATE_NONE,
				       NULL,
				       NULL,
				       error);
	if (!ret)
		goto out;
out:
	g_string_free (string, FALSE);
	return ret;
}
Ejemplo n.º 8
0
gboolean
timeout_func (gpointer user_data)
{
	char ** argv = (char **)user_data;

	g_usleep(500000);

	g_debug("Initing");

	gchar * command = g_strdup_printf("%s --dbus-name=org.dbusmenu.test --dbus-object=/org/test", argv[1]);
	g_debug("Executing: %s", command);

	gchar * output;
	g_spawn_command_line_sync(command, &output, NULL, NULL, NULL);

	GFile * ofile = g_file_new_for_commandline_arg(argv[2]);
	if (ofile != NULL) {
		g_file_replace_contents(ofile, output, g_utf8_strlen(output, -1), NULL, FALSE, 0, NULL, NULL, NULL);
	}

	g_spawn_command_line_sync("gdbus call --session --dest org.dbusmenu.test --object-path /org/test --method com.canonical.dbusmenu.Event 0 clicked \"<0>\" 0", NULL, NULL, NULL, NULL);

	g_main_loop_quit(mainloop);
	return TRUE;
}
Ejemplo n.º 9
0
gboolean
hd_pixbuf_utils_save (GFile         *file,
                      GdkPixbuf     *pixbuf,
                      const gchar   *type,
                      GCancellable  *cancellable,
                      GError       **error)
{
  gchar *buffer = NULL;
  gsize buffer_size;
  gboolean result;

  if (!gdk_pixbuf_save_to_buffer (pixbuf,
                                  &buffer,
                                  &buffer_size,
                                  type,
                                  error,
                                  NULL))
    return FALSE;

  result = g_file_replace_contents (file,
                                    buffer,
                                    buffer_size,
                                    NULL,
                                    FALSE,
                                    G_FILE_CREATE_NONE,
                                    NULL,
                                    cancellable,
                                    error);

  g_free (buffer);

  return result;
}
Ejemplo n.º 10
0
static void
save_session_settings (RBAudioscrobblerAccount *account)
{
    /* Save the current session */
    const char *rb_data_dir;
    char *file_path;
    GKeyFile *key_file;
    char *service_name;
    char *data;
    gsize data_length;
    GFile *out_file;
    GError *error;

    rb_data_dir = rb_user_data_dir ();
    if (rb_data_dir == NULL) {
        rb_debug ("error saving session: could not find data dir");
        return;
    }

    file_path = g_build_filename (rb_data_dir, "audioscrobbler", SESSION_SETTINGS_FILE, NULL);
    key_file = g_key_file_new ();
    /* load existing file contents. errors wont matter, just means file doesn't exist yet */
    g_key_file_load_from_file (key_file, file_path, G_KEY_FILE_KEEP_COMMENTS, NULL);

    /* get the service name */
    g_object_get (account->priv->service, "name", &service_name, NULL);

    /* set the new data */
    if (account->priv->username != NULL && account->priv->session_key != NULL) {
        g_key_file_set_string (key_file, service_name, "username", account->priv->username);
        g_key_file_set_string (key_file, service_name, "session_key", account->priv->session_key);
    } else {
        g_key_file_remove_group (key_file, service_name, NULL);
    }
    g_free (service_name);

    data = g_key_file_to_data (key_file, &data_length, NULL);
    g_key_file_free (key_file);

    /* write data to the file */
    out_file = g_file_new_for_path (file_path);
    g_free (file_path);

    error = NULL;
    g_file_replace_contents (out_file, data, data_length, NULL, FALSE, G_FILE_CREATE_NONE, NULL, NULL, &error);
    if (error != NULL) {
        rb_debug ("error saving session: %s", error->message);
        g_error_free (error);
    } else {
        rb_debug ("successfully saved session");
    }

    g_free (data);
    g_object_unref (out_file);
}
Ejemplo n.º 11
0
static gboolean
handle_userdata_script (MinCloudAgentApp      *self,
                        GInputStream               *instream,
                        GCancellable               *cancellable,
                        GError                    **error)
{
  gboolean ret = FALSE;
  gs_free char *tmppath = g_strdup ("/var/tmp/userdata-script.XXXXXX");
  gs_unref_object GOutputStream *outstream = NULL;
  int fd;

  fd = g_mkstemp_full (tmppath, O_WRONLY, 0700);
  if (fd == -1)
    {
      int errsv = errno;
      g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                   "Failed to create temporary userdata script: %s",
                   g_strerror (errsv));
      goto out;
    }
  outstream = g_unix_output_stream_new (fd, TRUE);

  if (0 > g_output_stream_splice ((GOutputStream*)outstream, instream,
                                  G_OUTPUT_STREAM_SPLICE_CLOSE_TARGET |
                                  G_OUTPUT_STREAM_SPLICE_CLOSE_SOURCE,
                                  self->cancellable, error))
    goto out;

  gs_log_structured_print_id_v (MCA_USERDATA_EXECUTING_ID,
                                "Executing user data script");

  if (!gs_subprocess_simple_run_sync (NULL, GS_SUBPROCESS_STREAM_DISPOSITION_NULL,
                                      cancellable, error,
                                      tmppath,
                                      NULL))
    {
      gs_log_structured_print_id_v (MCA_USERDATA_FAILED_ID,
                                    "User data script failed");
      goto out;
    }

  gs_log_structured_print_id_v (MCA_USERDATA_SUCCESS_ID,
                                "User data script suceeded");
  
  if (!g_file_replace_contents (self->userdata_done_stamp, "done\n", 5,
                                NULL, FALSE, 0,
                                NULL, cancellable, error))
    goto out;

  ret = TRUE;
 out:
  (void) unlink (tmppath);
  return ret;
}
Ejemplo n.º 12
0
static gboolean
builder_source_script_extract (BuilderSource *source,
                               GFile *dest,
                               BuilderContext *context,
                               GError **error)
{
  BuilderSourceScript *self = BUILDER_SOURCE_SCRIPT (source);
  g_autoptr(GFile) dest_script = NULL;
  const char *dest_filename;
  g_autoptr(GString) script = NULL;
  int i;
  guint32 perms;

  script = g_string_new ("#!/bin/sh\n");

  if (self->commands)
    {
      for (i = 0; self->commands[i] != NULL; i++)
        {
          g_string_append (script, self->commands[i]);
          g_string_append_c (script, '\n');
        }
    }

  if (self->dest_filename)
    dest_filename = self->dest_filename;
  else
    dest_filename = "autogen.sh";

  dest_script = g_file_get_child (dest, dest_filename);

  if (!g_file_replace_contents (dest_script,
                                script->str,
                                script->len,
                                NULL,
                                FALSE,
                                G_FILE_CREATE_REPLACE_DESTINATION,
                                NULL, NULL,error))
    return FALSE;

  perms = 0755;
  if (!g_file_set_attribute (dest_script,
                             G_FILE_ATTRIBUTE_UNIX_MODE,
                             G_FILE_ATTRIBUTE_TYPE_UINT32,
                             &perms,
                             G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
                             NULL, error))
    return FALSE;

  return TRUE;
}
Ejemplo n.º 13
0
/**
 * anjuta_profile_sync:
 * @profile: a #AnjutaProfile object.
 * @error: error propagation and reporting.
 * 
 * Save the current plugins list in the xml file set with anjuta_profile_set_sync_file().
 *
 * Return value: TRUE on success, FALSE otherwise.
 */
gboolean
anjuta_profile_sync (AnjutaProfile *profile, GError **error)
{
	gboolean ok;
	gchar *xml_buffer;
	AnjutaProfilePriv *priv;
	GError* file_error = NULL;
	
	g_return_val_if_fail (ANJUTA_IS_PROFILE (profile), FALSE);
	priv = profile->priv;
	
	if (!priv->sync_file)
		return FALSE;
	
	xml_buffer = anjuta_profile_to_xml (profile);
	ok = g_file_replace_contents (priv->sync_file, xml_buffer, strlen(xml_buffer),
								  NULL, FALSE, G_FILE_CREATE_NONE,
								  NULL, NULL, &file_error);
	if (!ok && g_error_matches (file_error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND))
	{
		/* Try to create parent directory */
		GFile* parent = g_file_get_parent (priv->sync_file);
		if (g_file_make_directory (parent, NULL, NULL))
		{
			g_clear_error (&file_error);
			ok = g_file_replace_contents (priv->sync_file, xml_buffer, strlen(xml_buffer),
										  NULL, FALSE, G_FILE_CREATE_NONE,
										  NULL, NULL, &file_error);
		}
		g_object_unref (parent);
	}
	g_free (xml_buffer);
	if (file_error != NULL) g_propagate_error (error, file_error);
	
	return ok;
}
Ejemplo n.º 14
0
static void
g_keyfile_settings_backend_keyfile_write (GKeyfileSettingsBackend *kfsb)
{
  gchar *contents;
  gsize length;

  contents = g_key_file_to_data (kfsb->keyfile, &length, NULL);
  g_file_replace_contents (kfsb->file, contents, length, NULL, FALSE,
                           G_FILE_CREATE_REPLACE_DESTINATION |
                           G_FILE_CREATE_PRIVATE,
                           NULL, NULL, NULL);

  compute_checksum (kfsb->digest, contents, length);
  g_free (contents);
}
Ejemplo n.º 15
0
/* Set everything up for using the NI compiler. Called from the main thread. */
static void
prepare_ni_compiler(CompilerData *data)
{
    I7_STORY_USE_PRIVATE(data->story, priv);
    GError *err = NULL;

    /* Clear the previous compile output */
    gtk_text_buffer_set_text(priv->progress, "", -1);
    html_load_blank(WEBKIT_WEB_VIEW(data->story->panel[LEFT]->results_tabs[I7_RESULTS_TAB_REPORT]));
    html_load_blank(WEBKIT_WEB_VIEW(data->story->panel[RIGHT]->results_tabs[I7_RESULTS_TAB_REPORT]));

    /* Create the UUID file if needed */
    GFile *uuid_file = g_file_get_child(data->input_file, "uuid.txt");
    if(!g_file_query_exists(uuid_file, NULL)) {
#ifdef E2FS_UUID /* code for e2fsprogs uuid */
        uuid_t uuid;
        gchar uuid_string[37];

        uuid_generate_time(uuid);
        uuid_unparse(uuid, uuid_string);
#else /* code for OSSP UUID */
        gchar *uuid_string = NULL; /* a new buffer is allocated if NULL */
        uuid_t *uuid;

        if(!((uuid_create(&uuid) == UUID_RC_OK)
                && (uuid_make(uuid, UUID_MAKE_V1) == UUID_RC_OK)
                && (uuid_export(uuid, UUID_FMT_STR, (void **)&uuid_string, NULL) == UUID_RC_OK)
                && (uuid_destroy(uuid) == UUID_RC_OK))) {
            error_dialog(GTK_WINDOW(data->story), NULL, _("Error creating UUID."));
            g_object_unref(uuid_file);
            return;
        }
#endif /* UUID conditional */
        if(!g_file_replace_contents(uuid_file, uuid_string, strlen(uuid_string), NULL, FALSE, G_FILE_CREATE_NONE, NULL, NULL, &err)) {
            IO_ERROR_DIALOG(GTK_WINDOW(data->story), uuid_file, err, _("creating UUID file"));
            g_object_unref(uuid_file);
            return;
        }
#ifndef E2FS_UUID /* Only OSSP UUID */
        free(uuid_string);
#endif /* !OSSP_UUID */
    }
    g_object_unref(uuid_file);

    /* Display status message */
    i7_document_display_status_message(I7_DOCUMENT(data->story), _("Compiling Inform 7 to Inform 6"), COMPILE_OPERATIONS);
}
Ejemplo n.º 16
0
static void
scrollback_shrink (session *sess)
{
	char *buf, *p;
	gsize len;
	gint offset, lines = 0;
	const gint max_lines = MIN(prefs.hex_text_max_lines, SCROLLBACK_MAX);

	if (!g_file_load_contents (sess->scrollfile, NULL, &buf, &len, NULL, NULL))
		return;

	/* count all lines */
	p = buf;
	while (p != buf + len)
	{
		if (*p == '\n')
			lines++;
		p++;
	}

	offset = lines - max_lines;

	/* now just go back to where we want to start the file */
	p = buf;
	lines = 0;
	while (p != buf + len)
	{
		if (*p == '\n')
		{
			lines++;
			if (lines == offset)
			{
				p++;
				break;
			}
		}
		p++;
	}

	if (g_file_replace_contents (sess->scrollfile, p, strlen(p), NULL, FALSE,
							G_FILE_CREATE_PRIVATE, NULL, NULL, NULL))
		sess->scrollwritten = lines;

	g_free (buf);
}
Ejemplo n.º 17
0
static void _dentry_ui_finish(gpointer pdata, gboolean cancelled)
{
    FmFilePropertiesDEntryData *data = pdata;
    gsize len;
    char *text;

    if (data == NULL)
        return;
    if (!cancelled)
    {
        text = g_object_get_qdata(data->icon, fm_qdata_id);
        if (text)
        {
            g_key_file_set_string(data->kf, GRP_NAME, "Icon", text);
            /* disable default handler for icon change since we'll do it below */
            g_object_set_qdata(data->icon, fm_qdata_id, NULL);
            data->changed = TRUE;
        }
    }
    if (!cancelled && data->changed)
    {
        text = g_key_file_to_data(data->kf, &len, NULL);
        g_file_replace_contents(data->file, text, len, NULL, FALSE, 0, NULL,
                                NULL, NULL);
        /* FIXME: handle errors */
        g_free(text);
    }
    g_object_unref(data->file);
    g_key_file_free(data->kf);
    /* disable own handler on data->name */
    g_signal_handlers_disconnect_by_func(data->name, _dentry_name_changed, data);
    /* restore the field so properties dialog will not do own processing */
    gtk_entry_set_text(data->name, data->saved_name);
    if (data->hidden)
    {
        /* disable own handler on data->hidden */
        g_signal_handlers_disconnect_by_func(data->hidden,
                                             _dentry_hidden_toggled, data);
        /* disable default handler returning previous value */
        gtk_toggle_button_set_active(data->hidden, data->was_hidden);
    }
    g_free(data->saved_name);
    g_free(data->lang);
    g_slice_free(FmFilePropertiesDEntryData, data);
}
Ejemplo n.º 18
0
static gboolean
replace_nsswitch (GFile         *target_usretc,
                  GCancellable  *cancellable,
                  GError       **error)
{
    gboolean ret = FALSE;
    gs_unref_object GFile *nsswitch_conf =
        g_file_get_child (target_usretc, "nsswitch.conf");
    gs_free char *nsswitch_contents = NULL;
    gs_free char *new_nsswitch_contents = NULL;

    static gsize regex_initialized;
    static GRegex *passwd_regex;

    if (g_once_init_enter (&regex_initialized))
    {
        passwd_regex = g_regex_new ("^(passwd|group):\\s+files(.*)$",
                                    G_REGEX_MULTILINE, 0, NULL);
        g_assert (passwd_regex);
        g_once_init_leave (&regex_initialized, 1);
    }

    nsswitch_contents = gs_file_load_contents_utf8 (nsswitch_conf, cancellable, error);
    if (!nsswitch_contents)
        goto out;

    new_nsswitch_contents = g_regex_replace (passwd_regex,
                            nsswitch_contents, -1, 0,
                            "\\1: files altfiles\\2",
                            0, error);
    if (!new_nsswitch_contents)
        goto out;

    if (!g_file_replace_contents (nsswitch_conf, new_nsswitch_contents,
                                  strlen (new_nsswitch_contents),
                                  NULL, FALSE, 0, NULL,
                                  cancellable, error))
        goto out;

    ret = TRUE;
out:
    return ret;
}
Ejemplo n.º 19
0
/**
 * as_node_to_file: (skip)
 * @root: A populated #AsNode tree
 * @file: a #GFile
 * @flags: #AsNodeToXmlFlags, e.g. %AS_NODE_TO_XML_FLAG_NONE
 * @cancellable: A #GCancellable, or %NULL
 * @error: A #GError or %NULL
 *
 * Exports a DOM tree to an XML file.
 *
 * Returns: %TRUE for success
 *
 * Since: 0.2.0
 **/
gboolean
as_node_to_file (const AsNode *root,
		 GFile *file,
		 AsNodeToXmlFlags flags,
		 GCancellable *cancellable,
		 GError **error)
{
	g_autoptr(GString) xml = NULL;
	xml = as_node_to_xml (root, flags);
	return g_file_replace_contents (file,
					xml->str,
					xml->len,
					NULL,
					FALSE,
					G_FILE_CREATE_NONE,
					NULL,
					cancellable,
					error);
}
Ejemplo n.º 20
0
gboolean put_stringlist(GFile * file, GList * which_list, gboolean is_arraylist) {
	/*return put_stringlist_limited(file,which_list, -1, is_arraylist);*/
	gchar *buf;
	GError *gerror=NULL;
	if (is_arraylist) {
		buf = arraylist_to_string(which_list, "\n");
	} else {
		buf = stringlist_to_string(which_list, "\n");
	}
	g_file_replace_contents(file,buf,strlen(buf)
				,NULL,FALSE,G_FILE_CREATE_PRIVATE,NULL,NULL,&gerror);
	if (gerror) {
		g_warning("save stringlist error %d %s\n",gerror->code,gerror->message);
		g_error_free(gerror);
		return FALSE;
	}
	g_free(buf);
	return TRUE;
}
Ejemplo n.º 21
0
static gboolean
amp_group_node_save (AmpNode *group, AmpNode *parent, AmpProject *project, GError **error)
{
	AnjutaTokenFile *tfile;
	AnjutaProjectNode *child;
	gboolean ok = TRUE;
	GFile *directory;

	/* Check if Makefile.am is missing, it happens in po directory by example */
	if (AMP_GROUP_NODE (group)->makefile == NULL) return FALSE;
	
	/* Create directory */
	directory = g_file_get_parent (AMP_GROUP_NODE (group)->makefile);
	g_file_make_directory (directory, NULL, NULL);
	g_object_unref (directory);

	/* Save group */
	tfile = AMP_GROUP_NODE (group)->tfile;
	if (tfile == NULL)
	{
		/* Create an empty makefile */
		g_file_replace_contents (AMP_GROUP_NODE (group)->makefile, "", 0, NULL, FALSE, G_FILE_CREATE_NONE, NULL, NULL, NULL);

		return TRUE;
	}

	if (anjuta_token_file_is_dirty (tfile))
	{
		if (!anjuta_token_file_save (tfile, error)) return FALSE;
	}

	/* Save all children */
	for (child = anjuta_project_node_first_child (ANJUTA_PROJECT_NODE (group)); child != NULL; child = anjuta_project_node_next_sibling (child))
	{
		/* Try to save all children even if some fail */
		if (!amp_node_save (AMP_NODE (child), group, project, error)) ok = FALSE;
	}

	return ok;
}
Ejemplo n.º 22
0
gboolean 
gtodo_client_export(GTodoClient *source, GFile *dest, const gchar *path_to_xsl, gchar **params, GError **error)
{
	xsltStylesheetPtr cur;
	xmlChar *string;
	xmlDocPtr res;
	int length;
	GError *err;

	g_return_val_if_fail(path_to_xsl != NULL, FALSE);

	cur= xsltParseStylesheetFile(BAD_CAST (path_to_xsl));

	if (params == NULL)
	{
		res = xsltApplyStylesheet(cur, source->gtodo_doc, NULL);
	}
	else
	{
		res = xsltApplyStylesheet(cur, source->gtodo_doc, (const char **)params);
	}

	xsltSaveResultToString (&string, &length, res, cur);

	if (!g_file_replace_contents (dest, (char *)string, length, NULL, FALSE,
			G_FILE_CREATE_NONE, NULL, NULL, &err))
	{
		DEBUG_PRINT ("Error exporting file: %s", 
				err->message);
		g_propagate_error (error, err);
	}

	xmlFree (string);
	xsltFreeStylesheet (cur);
	xmlFreeDoc (res);
	xsltCleanupGlobals ();

	return TRUE;
}
Ejemplo n.º 23
0
static void
save_clicked (GtkWidget *button,
              gpointer data)
{
    GString *s;
    GtkWidget *dialog;
    GFile *file;

    s = g_string_new ("");

    save_children (s, gtk_widget_get_window (darea));

    dialog = gtk_file_chooser_dialog_new ("Filename for window data",
                                          NULL,
                                          GTK_FILE_CHOOSER_ACTION_SAVE,
                                          GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
                                          GTK_STOCK_SAVE, GTK_RESPONSE_ACCEPT,
                                          NULL);

    gtk_file_chooser_set_do_overwrite_confirmation (GTK_FILE_CHOOSER (dialog), TRUE);

    if (gtk_dialog_run (GTK_DIALOG (dialog)) == GTK_RESPONSE_ACCEPT)
    {
        file = gtk_file_chooser_get_file (GTK_FILE_CHOOSER (dialog));

        g_file_replace_contents (file,
                                 s->str, s->len,
                                 NULL, FALSE,
                                 0, NULL, NULL, NULL);

        g_object_unref (file);
    }

    gtk_widget_destroy (dialog);
    g_string_free (s, TRUE);
}
Ejemplo n.º 24
0
static gboolean
_g_key_file_save_to_gfile (GKeyFile *key_file,
			   GFile *file,
			   GError  **error)
{
	char *data;
	gsize len;

	data = g_key_file_to_data (key_file, &len, error);
	if (data == NULL) {
		return FALSE;
	}
		
	if (!g_file_replace_contents (file,
				      data, len,
				      NULL, FALSE,
				      G_FILE_CREATE_NONE,
				      NULL, NULL, error)) {
		g_free (data);
		return FALSE;
	}
	g_free (data);
	return TRUE;
}
Ejemplo n.º 25
0
gboolean
nemo_link_local_create (const char     *directory_uri,
			    const char     *base_name,
			    const char     *display_name,
			    const char     *image,
			    const char     *target_uri,
			    const GdkPoint *point,
			    int             screen,
			    gboolean        unique_filename)
{
	char *real_directory_uri;
	char *uri, *contents;
	GFile *file;
	GList dummy_list;
	NemoFileChangesQueuePosition item;

	g_return_val_if_fail (directory_uri != NULL, FALSE);
	g_return_val_if_fail (base_name != NULL, FALSE);
	g_return_val_if_fail (display_name != NULL, FALSE);
	g_return_val_if_fail (target_uri != NULL, FALSE);

	if (eel_uri_is_trash (directory_uri) ||
	    eel_uri_is_search (directory_uri)) {
		return FALSE;
	}

	if (eel_uri_is_desktop (directory_uri)) {
		real_directory_uri = nemo_get_desktop_directory_uri ();
	} else {
		real_directory_uri = g_strdup (directory_uri);
	}

	if (unique_filename) {
		uri = nemo_ensure_unique_file_name (real_directory_uri,
							base_name, ".desktop");
		if (uri == NULL) {
			g_free (real_directory_uri);
			return FALSE;
		}
		file = g_file_new_for_uri (uri);
		g_free (uri);
	} else {
		char *link_name;
		GFile *dir;

		link_name = g_strdup_printf ("%s.desktop", base_name);

		/* replace '/' with '-', just in case */
		g_strdelimit (link_name, "/", '-');

		dir = g_file_new_for_uri (directory_uri);
		file = g_file_get_child (dir, link_name);

		g_free (link_name);
		g_object_unref (dir);
	}

	g_free (real_directory_uri);

	contents = g_strdup_printf ("[Desktop Entry]\n"
				    "Encoding=UTF-8\n"
				    "Name=%s\n"
				    "Type=Link\n"
				    "URL=%s\n"
				    "%s%s\n",
				    display_name,
				    target_uri,
				    image != NULL ? "Icon=" : "",
				    image != NULL ? image : "");


	if (!g_file_replace_contents (file,
				      contents, strlen (contents),
				      NULL, FALSE,
				      G_FILE_CREATE_NONE,
				      NULL, NULL, NULL)) {
		g_free (contents);
		g_object_unref (file);
		return FALSE;
	}
	g_free (contents);

	dummy_list.data = file;
	dummy_list.next = NULL;
	dummy_list.prev = NULL;
	nemo_directory_notify_files_added (&dummy_list);

	if (point != NULL) {
		item.location = file;
		item.set = TRUE;
		item.point.x = point->x;
		item.point.y = point->y;
		item.screen = screen;
		dummy_list.data = &item;
		dummy_list.next = NULL;
		dummy_list.prev = NULL;
	
		nemo_directory_schedule_position_set (&dummy_list);
	}

	g_object_unref (file);
	return TRUE;
}
Ejemplo n.º 26
0
static gboolean
do_kernel_prep (GFile         *yumroot,
                JsonObject    *treefile,
                GCancellable  *cancellable,
                GError       **error)
{
    gboolean ret = FALSE;
    gs_unref_object GFile *bootdir =
        g_file_get_child (yumroot, "boot");
    gs_unref_object GFile *kernel_path = NULL;
    gs_unref_object GFile *initramfs_path = NULL;
    const char *boot_checksum_str = NULL;
    GChecksum *boot_checksum = NULL;
    g_autofree char *kver = NULL;

    if (!find_kernel_and_initramfs_in_bootdir (bootdir, &kernel_path,
            &initramfs_path,
            cancellable, error))
        goto out;

    if (kernel_path == NULL)
    {
        gs_unref_object GFile *mod_dir = g_file_resolve_relative_path (yumroot, "usr/lib/modules");
        gs_unref_object GFile *modversion_dir = NULL;

        if (!find_ensure_one_subdirectory (mod_dir, &modversion_dir, cancellable, error))
            goto out;

        if (modversion_dir)
        {
            kver = g_file_get_basename (modversion_dir);
            if (!find_kernel_and_initramfs_in_bootdir (modversion_dir, &kernel_path,
                    &initramfs_path,
                    cancellable, error))
                goto out;
        }
    }

    if (kernel_path == NULL)
    {
        g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                     "Unable to find kernel (vmlinuz) in /boot or /usr/lib/modules");
        goto out;
    }

    if (initramfs_path)
    {
        g_print ("Removing RPM-generated '%s'\n",
                 gs_file_get_path_cached (initramfs_path));
        if (!gs_shutil_rm_rf (initramfs_path, cancellable, error))
            goto out;
    }

    if (!kver)
    {
        const char *kname = gs_file_get_basename_cached (kernel_path);
        const char *kver_p;

        kver_p = strchr (kname, '-');
        g_assert (kver_p);
        kver = g_strdup (kver_p + 1);
    }

    /* OSTree needs to own this */
    {
        gs_unref_object GFile *loaderdir = g_file_get_child (bootdir, "loader");
        if (!gs_shutil_rm_rf (loaderdir, cancellable, error))
            goto out;
    }

    {
        char *child_argv[] = { "depmod", (char*)kver, NULL };
        if (!run_sync_in_root (yumroot, "depmod", child_argv, error))
            goto out;
    }

    /* Ensure the /etc/machine-id file is present and empty. Apparently systemd
       doesn't work when the file is missing (as of systemd-219-9.fc22) but it is
       correctly populated if the file is there.  */
    g_print ("Creating empty machine-id\n");
    {
        const char *hardcoded_machine_id = "";
        gs_unref_object GFile *machineid_path =
            g_file_resolve_relative_path (yumroot, "etc/machine-id");
        if (!g_file_replace_contents (machineid_path, hardcoded_machine_id,
                                      strlen (hardcoded_machine_id),
                                      NULL, FALSE, 0, NULL,
                                      cancellable, error))
            goto out;
    }

    {
        gboolean reproducible;
        gs_unref_ptrarray GPtrArray *dracut_argv = g_ptr_array_new ();

        if (!dracut_supports_reproducible (yumroot, &reproducible, cancellable, error))
            goto out;

        g_ptr_array_add (dracut_argv, "dracut");
        g_ptr_array_add (dracut_argv, "-v");
        if (reproducible)
        {
            g_ptr_array_add (dracut_argv, "--reproducible");
            g_ptr_array_add (dracut_argv, "--gzip");
        }
        g_ptr_array_add (dracut_argv, "--tmpdir=/tmp");
        g_ptr_array_add (dracut_argv, "-f");
        g_ptr_array_add (dracut_argv, "/var/tmp/initramfs.img");
        g_ptr_array_add (dracut_argv, (char*)kver);

        if (json_object_has_member (treefile, "initramfs-args"))
        {
            guint i, len;
            JsonArray *initramfs_args;

            initramfs_args = json_object_get_array_member (treefile, "initramfs-args");
            len = json_array_get_length (initramfs_args);

            for (i = 0; i < len; i++)
            {
                const char *arg = _rpmostree_jsonutil_array_require_string_element (initramfs_args, i, error);
                if (!arg)
                    goto out;
                g_ptr_array_add (dracut_argv, (char*)arg);
            }
        }

        g_ptr_array_add (dracut_argv, NULL);

        if (!run_sync_in_root (yumroot, "dracut", (char**)dracut_argv->pdata, error))
            goto out;
    }

    initramfs_path = g_file_resolve_relative_path (yumroot, "var/tmp/initramfs.img");
    if (!g_file_query_exists (initramfs_path, NULL))
    {
        g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                     "Dracut failed to generate '%s'",
                     gs_file_get_path_cached (initramfs_path));
        goto out;
    }

    {
        gs_free char *initramfs_name = g_strconcat ("initramfs-", kver, ".img", NULL);
        gs_unref_object GFile *initramfs_dest =
            g_file_get_child (bootdir, initramfs_name);

        if (!gs_file_rename (initramfs_path, initramfs_dest,
                             cancellable, error))
            goto out;

        /* Transfer ownership */
        g_object_unref (initramfs_path);
        initramfs_path = initramfs_dest;
        initramfs_dest = NULL;
    }

    boot_checksum = g_checksum_new (G_CHECKSUM_SHA256);
    if (!_rpmostree_util_update_checksum_from_file (boot_checksum, kernel_path,
            cancellable, error))
        goto out;
    if (!_rpmostree_util_update_checksum_from_file (boot_checksum, initramfs_path,
            cancellable, error))
        goto out;

    boot_checksum_str = g_checksum_get_string (boot_checksum);

    {
        gs_free char *new_kernel_name =
            g_strconcat (gs_file_get_basename_cached (kernel_path), "-",
                         boot_checksum_str, NULL);
        gs_unref_object GFile *new_kernel_path =
            g_file_get_child (bootdir, new_kernel_name);
        gs_free char *new_initramfs_name =
            g_strconcat (gs_file_get_basename_cached (initramfs_path), "-",
                         boot_checksum_str, NULL);
        gs_unref_object GFile *new_initramfs_path =
            g_file_get_child (bootdir, new_initramfs_name);

        if (!gs_file_rename (kernel_path, new_kernel_path,
                             cancellable, error))
            goto out;
        if (!gs_file_rename (initramfs_path, new_initramfs_path,
                             cancellable, error))
            goto out;
    }

    ret = TRUE;
out:
    if (boot_checksum) g_checksum_free (boot_checksum);
    return ret;
}
Ejemplo n.º 27
0
gboolean
rpmostree_treefile_postprocessing (GFile         *yumroot,
                                   GFile         *context_directory,
                                   GBytes        *serialized_treefile,
                                   JsonObject    *treefile,
                                   GCancellable  *cancellable,
                                   GError       **error)
{
    gboolean ret = FALSE;
    guint i, len;
    JsonArray *units = NULL;
    JsonArray *remove = NULL;
    const char *default_target = NULL;
    const char *postprocess_script = NULL;

    if (json_object_has_member (treefile, "units"))
        units = json_object_get_array_member (treefile, "units");

    if (units)
        len = json_array_get_length (units);
    else
        len = 0;

    {
        gs_unref_object GFile *multiuser_wants_dir =
            g_file_resolve_relative_path (yumroot, "etc/systemd/system/multi-user.target.wants");

        if (!gs_file_ensure_directory (multiuser_wants_dir, TRUE, cancellable, error))
            goto out;

        for (i = 0; i < len; i++)
        {
            const char *unitname = _rpmostree_jsonutil_array_require_string_element (units, i, error);
            gs_unref_object GFile *unit_link_target = NULL;
            gs_free char *symlink_target = NULL;

            if (!unitname)
                goto out;

            symlink_target = g_strconcat ("/usr/lib/systemd/system/", unitname, NULL);
            unit_link_target = g_file_get_child (multiuser_wants_dir, unitname);

            if (g_file_query_file_type (unit_link_target, G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS, NULL) == G_FILE_TYPE_SYMBOLIC_LINK)
                continue;

            g_print ("Adding %s to multi-user.target.wants\n", unitname);

            if (!g_file_make_symbolic_link (unit_link_target, symlink_target,
                                            cancellable, error))
                goto out;
        }
    }

    {
        gs_unref_object GFile *target_treefile_dir_path =
            g_file_resolve_relative_path (yumroot, "usr/share/rpm-ostree");
        gs_unref_object GFile *target_treefile_path =
            g_file_get_child (target_treefile_dir_path, "treefile.json");
        const guint8 *buf;
        gsize len;

        if (!gs_file_ensure_directory (target_treefile_dir_path, TRUE,
                                       cancellable, error))
            goto out;

        g_print ("Writing '%s'\n", gs_file_get_path_cached (target_treefile_path));
        buf = g_bytes_get_data (serialized_treefile, &len);

        if (!g_file_replace_contents (target_treefile_path, (char*)buf, len,
                                      NULL, FALSE, G_FILE_CREATE_REPLACE_DESTINATION,
                                      NULL, cancellable, error))
            goto out;
    }

    if (!_rpmostree_jsonutil_object_get_optional_string_member (treefile, "default_target",
            &default_target, error))
        goto out;

    if (default_target != NULL)
    {
        gs_unref_object GFile *default_target_path =
            g_file_resolve_relative_path (yumroot, "etc/systemd/system/default.target");
        gs_free char *dest_default_target_path =
            g_strconcat ("/usr/lib/systemd/system/", default_target, NULL);

        (void) gs_file_unlink (default_target_path, NULL, NULL);

        if (!g_file_make_symbolic_link (default_target_path, dest_default_target_path,
                                        cancellable, error))
            goto out;
    }

    if (json_object_has_member (treefile, "remove-files"))
    {
        remove = json_object_get_array_member (treefile, "remove-files");
        len = json_array_get_length (remove);
    }
    else
        len = 0;

    for (i = 0; i < len; i++)
    {
        const char *val = _rpmostree_jsonutil_array_require_string_element (remove, i, error);
        gs_unref_object GFile *child = NULL;

        if (!val)
            return FALSE;
        if (g_path_is_absolute (val))
        {
            g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                         "'remove' elements must be relative");
            goto out;
        }

        child = g_file_resolve_relative_path (yumroot, val);

        if (g_file_query_exists (child, NULL))
        {
            g_print ("Removing '%s'\n", val);
            if (!gs_shutil_rm_rf (child, cancellable, error))
                goto out;
        }
        else
        {
            g_printerr ("warning: Targeted path for remove-files does not exist: %s\n",
                        gs_file_get_path_cached (child));
        }
    }

    if (json_object_has_member (treefile, "remove-from-packages"))
    {
        g_autoptr(RpmOstreeRefSack) refsack = NULL;
        _cleanup_hypackagelist_ HyPackageList pkglist = NULL;
        guint i;

        remove = json_object_get_array_member (treefile, "remove-from-packages");
        len = json_array_get_length (remove);

        if (!rpmostree_get_pkglist_for_root (AT_FDCWD, gs_file_get_path_cached (yumroot),
                                             &refsack, &pkglist,
                                             cancellable, error))
        {
            g_prefix_error (error, "Reading package set: ");
            goto out;
        }

        for (i = 0; i < len; i++)
        {
            JsonArray *elt = json_array_get_array_element (remove, i);
            if (!handle_remove_files_from_package (yumroot, refsack, elt, cancellable, error))
                goto out;
        }
    }

    if (!_rpmostree_jsonutil_object_get_optional_string_member (treefile, "postprocess-script",
            &postprocess_script, error))
        goto out;

    if (postprocess_script)
    {
        const char *yumroot_path = gs_file_get_path_cached (yumroot);
        gs_unref_object GFile *src = g_file_resolve_relative_path (context_directory, postprocess_script);
        const char *bn = gs_file_get_basename_cached (src);
        gs_free char *binpath = g_strconcat ("/usr/bin/rpmostree-postprocess-", bn, NULL);
        gs_free char *destpath = g_strconcat (yumroot_path, binpath, NULL);
        gs_unref_object GFile *dest = g_file_new_for_path (destpath);
        /* Clone all the things */

        if (!g_file_copy (src, dest, 0, cancellable, NULL, NULL, error))
        {
            g_prefix_error (error, "Copying postprocess-script '%s' into target: ", bn);
            goto out;
        }

        g_print ("Executing postprocessing script '%s'\n", bn);

        {
            char *child_argv[] = { binpath, NULL };
            if (!run_sync_in_root (yumroot, binpath, child_argv, error))
            {
                g_prefix_error (error, "While executing postprocessing script '%s': ", bn);
                goto out;
            }
        }

        g_print ("Finished postprocessing script '%s'\n", bn);
    }

    ret = TRUE;
out:
    return ret;
}
Ejemplo n.º 28
0
static gboolean
builder_source_file_extract (BuilderSource *source,
                             GFile *dest,
                             BuilderContext *context,
                             GError **error)
{
  BuilderSourceFile *self = BUILDER_SOURCE_FILE (source);
  g_autoptr(GFile) src = NULL;
  g_autoptr(GFile) dest_file = NULL;
  g_autofree char *dest_filename = NULL;
  gboolean is_local, is_inline;

  src = get_source_file (self, context, &is_local, &is_inline, error);
  if (src == NULL)
    return FALSE;

  if (self->dest_filename)
    dest_filename = g_strdup (self->dest_filename);
  else
    {
      if (is_inline)
        {
          g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                       "No dest-filename set for inline file data");
          return FALSE;
        }
      dest_filename = g_file_get_basename (src);
    }

  dest_file = g_file_get_child (dest, dest_filename);

  if (is_inline)
    {
      g_autoptr(GBytes) content = NULL;

      content = download_uri (self->url,
                              context,
                              error);
      if (content == NULL)
        return FALSE;

      if (!g_file_replace_contents (dest_file,
                                    g_bytes_get_data (content, NULL),
                                    g_bytes_get_size (content),
                                    NULL, FALSE, G_FILE_CREATE_NONE, NULL,
                                    NULL, error))
        return FALSE;
    }
  else
    {
      if (is_local)
        {
          g_autofree char *data = NULL;
          g_autofree char *base64 = NULL;
          gsize len;

          if (!g_file_load_contents (src, NULL, &data, &len, NULL, error))
            return FALSE;

          base64 = g_base64_encode ((const guchar *)data, len);
          g_free (self->url);
          self->url = g_strdup_printf ("data:text/plain;charset=utf8;base64,%s", base64);
          if (self->dest_filename == NULL || *self->dest_filename == 0)
            {
              g_free (self->dest_filename);
              self->dest_filename = g_file_get_basename (src);
            }
        }

      if (!g_file_copy (src, dest_file,
                        G_FILE_COPY_OVERWRITE,
                        NULL,
                        NULL, NULL,
                        error))
        return FALSE;
    }

  return TRUE;
}
Ejemplo n.º 29
0
static gboolean
builder_source_file_download (BuilderSource *source,
                              gboolean update_vcs,
                              BuilderContext *context,
                              GError **error)
{
  BuilderSourceFile *self = BUILDER_SOURCE_FILE (source);
  g_autoptr(GFile) file = NULL;
  gboolean is_local, is_inline;
  g_autoptr (GFile) dir = NULL;
  g_autofree char *dir_path = NULL;
  g_autofree char *sha256 = NULL;
  g_autofree char *base_name = NULL;
  g_autoptr(GBytes) content = NULL;

  file = get_source_file (self, context, &is_local, &is_inline, error);
  if (file == NULL)
    return FALSE;

  base_name = g_file_get_basename (file);

  if (g_file_query_exists (file, NULL))
    {
      if (is_local && self->sha256 != NULL && *self->sha256 != 0)
        {
          g_autofree char *data = NULL;
          gsize len;

          if (!g_file_load_contents (file, NULL, &data, &len, NULL, error))
            return FALSE;

          sha256 = g_compute_checksum_for_string (G_CHECKSUM_SHA256, data, len);
          if (strcmp (sha256, self->sha256) != 0)
            {
              g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                           "Wrong sha256 for %s, expected %s, was %s", base_name, self->sha256, sha256);
              return FALSE;
            }
        }
      return TRUE;
    }

  if (is_local)
    {
      g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED, "Can't find file at %s", self->path);
      return FALSE;
    }

  content = download_uri (self->url,
                          context,
                          error);
  if (content == NULL)
    return FALSE;

  sha256 = g_compute_checksum_for_string (G_CHECKSUM_SHA256,
                                          g_bytes_get_data (content, NULL),
                                          g_bytes_get_size (content));

  /* sha256 is optional for inline data */
  if (((self->sha256 != NULL && *self->sha256 != 0) || !is_inline) &&
      strcmp (sha256, self->sha256) != 0)
    {
      g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                   "Wrong sha256 for %s, expected %s, was %s", base_name, self->sha256, sha256);
      return FALSE;
    }

  dir = g_file_get_parent (file);
  dir_path = g_file_get_path (dir);
  g_mkdir_with_parents (dir_path, 0755);

  if (!g_file_replace_contents (file,
                                g_bytes_get_data (content, NULL),
                                g_bytes_get_size (content),
                                NULL, FALSE, G_FILE_CREATE_NONE, NULL,
                                NULL, error))
    return FALSE;

  return TRUE;
}
Ejemplo n.º 30
0
gboolean
flatpak_builtin_build_init (int argc, char **argv, GCancellable *cancellable, GError **error)
{
  g_autoptr(GOptionContext) context = NULL;
  g_autoptr(GFile) var_deploy_files = NULL;
  g_autoptr(GFile) base = NULL;
  g_autoptr(GFile) files_dir = NULL;
  g_autoptr(GFile) usr_dir = NULL;
  g_autoptr(GFile) var_dir = NULL;
  g_autoptr(GFile) var_tmp_dir = NULL;
  g_autoptr(GFile) var_run_dir = NULL;
  g_autoptr(GFile) metadata_file = NULL;
  g_autoptr(GString) metadata_contents = NULL;
  g_autoptr(GError) my_error = NULL;
  const char *app_id;
  const char *directory;
  const char *sdk;
  const char *runtime;
  const char *branch = "master";
  g_autofree char *runtime_ref = NULL;
  g_autofree char *var_ref = NULL;
  g_autofree char *sdk_ref = NULL;
  int i;

  context = g_option_context_new (_("DIRECTORY APPNAME SDK RUNTIME [BRANCH] - Initialize a directory for building"));
  g_option_context_set_translation_domain (context, GETTEXT_PACKAGE);

  if (!flatpak_option_context_parse (context, options, &argc, &argv, FLATPAK_BUILTIN_FLAG_NO_DIR, NULL, cancellable, error))
    return FALSE;

  if (argc < 5)
    return usage_error (context, _("RUNTIME must be specified"), error);

  if (argc > 6)
    return usage_error (context, _("Too many arguments"), error);

  directory = argv[1];
  app_id = argv[2];
  sdk = argv[3];
  runtime = argv[4];
  if (argc >= 6)
    branch = argv[5];

  if (!flatpak_is_valid_name (app_id, &my_error))
    return flatpak_fail (error, _("'%s' is not a valid application name: %s"), app_id, my_error->message);

  if (!flatpak_is_valid_name (runtime, &my_error))
    return flatpak_fail (error, _("'%s' is not a valid runtime name: %s"), runtime, my_error->message);

  if (!flatpak_is_valid_name (sdk, &my_error))
    return flatpak_fail (error, _("'%s' is not a valid sdk name: %s"), sdk, my_error->message);

  if (!flatpak_is_valid_branch (branch, &my_error))
    return flatpak_fail (error, _("'%s' is not a valid branch name: %s"), branch, my_error->message);

  runtime_ref = flatpak_build_untyped_ref (runtime, branch, opt_arch);
  sdk_ref = flatpak_build_untyped_ref (sdk, branch, opt_arch);

  base = g_file_new_for_commandline_arg (directory);

  if (!flatpak_mkdir_p (base, cancellable, error))
    return FALSE;

  files_dir = g_file_get_child (base, "files");
  if (opt_sdk_dir)
    usr_dir = g_file_get_child (base, opt_sdk_dir);
  else
    usr_dir = g_file_get_child (base, "usr");
  var_dir = g_file_get_child (base, "var");
  var_tmp_dir = g_file_get_child (var_dir, "tmp");
  var_run_dir = g_file_get_child (var_dir, "run");
  metadata_file = g_file_get_child (base, "metadata");

  if (!opt_update &&
      g_file_query_exists (files_dir, cancellable))
    return flatpak_fail (error, _("Build directory %s already initialized"), directory);

  if (opt_writable_sdk)
    {
      g_autofree char *full_sdk_ref = g_strconcat ("runtime/", sdk_ref, NULL);
      g_autoptr(GFile) sdk_deploy_files = NULL;
      g_autoptr(FlatpakDeploy) sdk_deploy = NULL;

      sdk_deploy = flatpak_find_deploy_for_ref (full_sdk_ref, cancellable, error);
      if (sdk_deploy == NULL)
        return FALSE;

      if (!flatpak_rm_rf (usr_dir, NULL, &my_error))
        {
          if (!g_error_matches (my_error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND))
            {
              g_propagate_error (error, g_steal_pointer (&my_error));
              return FALSE;
            }

          g_clear_error (&my_error);
        }

      sdk_deploy_files = flatpak_deploy_get_files (sdk_deploy);
      if (!flatpak_cp_a (sdk_deploy_files, usr_dir, FLATPAK_CP_FLAGS_NO_CHOWN, cancellable, error))
        return FALSE;

      if (opt_sdk_extensions &&
          !copy_extensions (sdk_deploy, branch, opt_sdk_extensions, usr_dir, cancellable, error))
        return FALSE;
    }

  if (opt_var)
    {
      var_ref = flatpak_build_runtime_ref (opt_var, branch, opt_arch);

      var_deploy_files = flatpak_find_files_dir_for_ref (var_ref, cancellable, error);
      if (var_deploy_files == NULL)
        return FALSE;
    }

  if (opt_update)
    return TRUE;

  if (!g_file_make_directory (files_dir, cancellable, error))
    return FALSE;

  if (opt_base)
    {
      const char *base_branch;
      g_autofree char *base_ref = NULL;
      g_autoptr(GFile) base_deploy_files = NULL;
      g_autoptr(FlatpakDeploy) base_deploy = NULL;

      base_branch = opt_base_version ? opt_base_version : "master";
      base_ref = flatpak_build_app_ref (opt_base, base_branch, opt_arch);
      base_deploy = flatpak_find_deploy_for_ref (base_ref, cancellable, error);
      if (base_deploy == NULL)
        return FALSE;

      base_deploy_files = flatpak_deploy_get_files (base_deploy);
      if (!flatpak_cp_a (base_deploy_files, files_dir,
                         FLATPAK_CP_FLAGS_MERGE | FLATPAK_CP_FLAGS_NO_CHOWN,
                         cancellable, error))
        return FALSE;


      if (opt_base_extensions &&
          !copy_extensions (base_deploy, base_branch, opt_base_extensions, files_dir, cancellable, error))
        return FALSE;
    }

  if (var_deploy_files)
    {
      if (!flatpak_cp_a (var_deploy_files, var_dir, FLATPAK_CP_FLAGS_NONE, cancellable, error))
        return FALSE;
    }
  else
    {
      if (!g_file_make_directory (var_dir, cancellable, error))
        return FALSE;
    }

  if (!flatpak_mkdir_p (var_tmp_dir, cancellable, error))
    return FALSE;

  if (!g_file_query_exists (var_run_dir, cancellable) &&
      !g_file_make_symbolic_link (var_run_dir, "/run", cancellable, error))
    return FALSE;


  metadata_contents = g_string_new ("[Application]\n");
  g_string_append_printf (metadata_contents,
                          "name=%s\n"
                          "runtime=%s\n"
                          "sdk=%s\n",
                          app_id, runtime_ref, sdk_ref);
  if (opt_tags != NULL)
    {
      g_string_append (metadata_contents, "tags=");
      for (i = 0; opt_tags[i] != NULL; i++)
        {
          g_string_append (metadata_contents, opt_tags[i]);
          g_string_append_c (metadata_contents, ';');
        }
      g_string_append_c (metadata_contents, '\n');
    }

  if (!g_file_replace_contents (metadata_file,
                                metadata_contents->str, metadata_contents->len, NULL, FALSE,
                                G_FILE_CREATE_REPLACE_DESTINATION,
                                NULL, cancellable, error))
    return FALSE;

  return TRUE;
}