bool folder_delete (const std::string& directory, bool recurse)
{
  std::string dir = directory;
  if (dir.empty()) dir = ".";
  if (!folder_exists(dir)) return false;
  bool result = true;
  // depth-first traversal ensures that directory contents are deleted before trying to delete the directory itself
  if (recurse)
  {
    std::vector<std::string> subdirectories = folder_subdirectories(dir);
    for (std::vector<std::string>::size_type d = 0; d < subdirectories.size(); ++d)
      if (!folder_delete(folder_down(dir,subdirectories[d]),true)) 
	result = false;
    std::vector<std::string> files = folder_files(dir);
    for (std::vector<std::string>::size_type f = 0; f < files.size(); ++f)
      if (!file_delete(create_filespec(dir, files[f]))) 
	result = false;
  }
  if (rmdir(dir.c_str())!=0) result = false;
  return result;
}
Esempio n. 2
0
END_TEST

START_TEST (test_nsdata_read_double)
{
  hid_t fid, sid;
  char data_name[] = "Test Non-Series DOUBLE";
  int iseed = 2090;
  herr_t err;
  int dim = generate_random_bound_int(1,3,&iseed);
  int *dimensions;
  double *data, *read_data;
  int data_size,idx;

  generate_output_file(&fid,&sid);

  dimensions = DANU_MALLOC(int,dim);
  data_size = 1;
  for(idx=0; idx < dim; idx++) {
    dimensions[idx] = generate_random_bound_int(10,1024,&iseed);
    data_size*=dimensions[idx];
  }
  data = DANU_MALLOC(double,data_size);
  read_data = DANU_MALLOC(double,data_size);

  generate_random_double_data(data,data_size,&iseed);


  data_write_double(sid,data_name,dim, dimensions, data);

  err = data_read_double(sid,data_name,dim,dimensions,read_data);
  fail_unless(memcmp(read_data,data,sizeof(double)*data_size) == 0,
              "Failed to read correct DOUBLE data");

  DANU_FREE(dimensions);
  DANU_FREE(data);
  DANU_FREE(read_data);

  file_delete();

}
Esempio n. 3
0
void download_is_finished(void *data, const char *file, int status){
	printf("\nDone (status: %d)\n", status);
	download_status = status;
	if(status == 200 && !is_abort){
		override_text(&download_perc, "d_perc_text", "Installing..");
		ecore_main_loop_iterate();
		switch(Apps[category].type_file[app+(y*3+x)]){
			case PSC_PACKAGE:
				Create_Bubble(file, Apps[category].name[app+(y*3+x)].c_str());
				pkg_is_installed = true;
				break;
			case PSC_THEME:
				Copy_Theme(file, Apps[category].name[app+(y*3+x)].c_str());
				break;
			case PSC_IMAGE:
			// /dev_hdd0/photo
				break;
			case PSC_VIDEO:
				break;
			default:
				break;
		}
	}
	override_text(&download_perc, "d_perc_text", "Deleting cache..");
	ecore_main_loop_iterate();
	file_delete(file);
	sleep(1);
	is_downloading = false;
 	hide_obj(down);
 	hide_edj(&download_perc);
	hide_edj(&download);
	is_download = false;
	if(!is_abort){
		is_asking_exit_to_xmb = true;
		show_edj(&download_ask);
	}else
		is_abort = false;
	evas_object_resize(down, 0, Bar_Y_Val);
}
Esempio n. 4
0
static BU_UINT8 media_fdel_msg_proc(media_handle_t mhandle, prot_handle_t phandle, void* msg, BU_UINT32 msg_len)
{
	char* sendBuf = NULL;
	BU_UINT32 ulOffSet = 0;
	BU_UINT32 ulPathLen = 0;
	char* path = NULL;
	pkt_mhead_t mhead;
	BU_UINT32 ulResult = BU_OK;
		
	UNPKG_UINT32_MSG(msg, ulOffSet, ulPathLen);
	if((path = (char*)calloc(1, ulPathLen)) == NULL){
		E_LOG("calloc error\n");
		return BU_ERROR;
	}
	UNPKG_BYTES_MSG(msg,ulOffSet, ulPathLen, path);


	ulResult = file_delete(path);


	/* ****************pkg prot PKG_PROT_MEDIA_FDEL_ACK************** 
		+4B: result code 
		
	*********************************************************** */
	ulOffSet = 0;
	mhead.media_handle = mhandle;
	mhead.prot_handle = phandle;
	mhead.type = PKG_PROT_MEDIA_FDEL_ACK;
	
	PKG_INIT_BUFF(sendBuf, sizeof(pkt_mhead_t) + 4);
    PKG_BYTES_MSG(sendBuf, ulOffSet, &mhead, sizeof(pkt_mhead_t));
	PKG_UINT32_MSG(sendBuf, ulOffSet, ulResult);
	msg_list_push(sendBuf, ulOffSet, PROT_TASK_ID, MEDIA_TASK_ID); 
	PKG_FREE_BUFF(sendBuf);
	free(path);
	
	return BU_OK;

}
Esempio n. 5
0
function run()
{
    if(!is(TRADEMODE)) {
        quit("Click [Trade] to update assets!");
        return;
    }

    LookBack = 0;
    StartDate = 2014; // set date for downloading price history
    EndDate = 2015;

#ifdef PRICE_HISTORY
#ifdef MAX_GAP
    GapDays = MAX_GAP;      // detect gaps
#endif
#else
    NumYears = -1; // don't load prices, only update Assets.dta
#endif
    string name;
#ifdef ADD_ASSET // add single asset
    name = ADD_ASSET;
    asset(name);
#else
#ifdef ALL_ASSETS // update all assets; add assets as you need
    while(name = loop("EUR/USD", "GBP/USD"))
#endif
#endif
    {
        asset(name);
        char content[100];
        sprintf(content,"Asset = %s\nStartYear = %i\nEndYear = %i\n\Path = %s", name, StartDate, EndDate, SAVE_PATH);
        file_write ("Plugin//${assemblyName}//HistoryConfig.properties", content, 0);
        var result = brokerCommand(666, 0);
        if(result == 0)
            quit("Error fetching history! Check logfile.");
        file_delete("Plugin//${assemblyName}//HistoryConfig.properties");
    }
    quit("Done!");
}
Esempio n. 6
0
static void file_write(struct file_info *file, int fd)
{
	off_t offset;
	size_t size, actual;
	unsigned seed;
	int truncate = 0;

	if (can_mmap && !full && !file->deleted && tests_random_no(100) == 1) {
		file_mmap_write(file);
		return;
	}

	get_offset_and_size(file, &offset, &size);
	seed = tests_random_no(10000000);
	actual = file_write_data(file, fd, offset, size, seed);

	if (offset + actual <= file->length && shrink)
		/* 1 time in 100, when shrinking
		   truncate after the write */
		if (tests_random_no(100) == 0)
			truncate = 1;

	if (actual != 0)
		file_write_info(file, offset, actual, seed);

	/* Delete errored files */
	if (!check_nospc_files && file->no_space_error) {
		file_delete(file);
		return;
	}

	if (truncate) {
		size_t new_length = offset + actual;
		if (file_ftruncate(file, fd, new_length))
			file_truncate_info(file, new_length);
	}
}
Esempio n. 7
0
/* Randomly select something to do with a directory entry */
static void operate_on_entry(struct dir_entry_info *entry)
{
	/* 1 time in 1000 rename */
	if (tests_random_no(1000) == 0) {
		rename_entry(entry);
		return;
	}
	if (entry->type == 's') {
		symlink_check(entry->entry.symlink);
		/* If shrinking, 1 time in 50, remove a symlink */
		if (shrink && tests_random_no(50) == 0)
			symlink_remove(entry->entry.symlink);
		return;
	}
	if (entry->type == 'd') {
		/* If shrinking, 1 time in 50, remove a directory */
		if (shrink && tests_random_no(50) == 0) {
			dir_remove(entry->entry.dir);
			return;
		}
		operate_on_dir(entry->entry.dir);
	}
	if (entry->type == 'f') {
		/* If shrinking, 1 time in 10, remove a file */
		if (shrink && tests_random_no(10) == 0) {
			file_delete(entry->entry.file);
			return;
		}
		/* If not growing, 1 time in 10, unlink a file with links > 1 */
		if (!grow && entry->entry.file->link_count > 1 &&
		    tests_random_no(10) == 0) {
			file_unlink_file(entry->entry.file);
			return;
		}
		operate_on_file(entry->entry.file);
	}
}
Esempio n. 8
0
// hddtype = 0:5MB / 1:10MB / 2:15MB / 3:20MB / 5:30MB / 6:40MB
void newdisk_hdi(const OEMCHAR *fname, UINT hddtype) {

const SASIHDD	*sasi;
	FILEH		fh;
	HDIHDR		hdi;
	UINT32		size;
	BRESULT		r;

	hddtype &= 7;
	if ((fname == NULL) || (hddtype == 7)) {
		goto ndhdi_err;
	}
	sasi = sasihdd + hddtype;
	fh = file_create(fname);
	if (fh == FILEH_INVALID) {
		goto ndhdi_err;
	}
	ZeroMemory(&hdi, sizeof(hdi));
	size = 256 * sasi->sectors * sasi->surfaces * sasi->cylinders;
//	STOREINTELDWORD(hdi.hddtype, 0);
	STOREINTELDWORD(hdi.headersize, 4096);
	STOREINTELDWORD(hdi.hddsize, size);
	STOREINTELDWORD(hdi.sectorsize, 256);
	STOREINTELDWORD(hdi.sectors, sasi->sectors);
	STOREINTELDWORD(hdi.surfaces, sasi->surfaces);
	STOREINTELDWORD(hdi.cylinders, sasi->cylinders);
	r = (file_write(fh, &hdi, sizeof(hdi)) == sizeof(hdi)) ? SUCCESS : FAILURE;
	r |= writezero(fh, 4096 - sizeof(hdi));
	r |= writehddipl(fh, 256, size);
	file_close(fh);
	if (r != SUCCESS) {
		file_delete(fname);
	}

ndhdi_err:
	return;
}
Esempio n. 9
0
static void dir_remove(struct dir_info *dir)
{
	char *path;
	struct dir_entry_info *entry;
	struct dir_entry_info **prev;
	int found;

	/* Remove directory contents */
	while (dir->first) {
		struct dir_entry_info *entry;

		entry = dir->first;
		if (entry->type == 'd')
			dir_remove(entry->entry.dir);
		else if (entry->type == 'f')
			file_delete(entry->entry.file);
		else
			CHECK(0); /* Invalid struct dir_entry_info */
	}
	/* Remove entry from parent directory */
	found = 0;
	prev = &dir->parent->first;
	for (entry = dir->parent->first; entry; entry = entry->next) {
		if (entry->type == 'd' && entry->entry.dir == dir) {
			dir->parent->number_of_entries -= 1;
			*prev = entry->next;
			free(entry);
			found = 1;
			break;
		}
		prev = &entry->next;
	}
	CHECK(found); /* Check the file is in the parent directory */
	/* Remove directory itself */
	path = dir_path(dir->parent, dir->name);
	CHECK(rmdir(path) != -1);
}
Esempio n. 10
0
END_TEST
START_TEST (test_nsdata_write_float)
{
  hid_t fid, sid;
  char data_name[] = "Test Non-Series FLOAT";
  int iseed = 10;
  herr_t err;
  int dim = generate_random_bound_int(1,3,&iseed);
  int *dimensions;
  float *data;
  int data_size,idx;

  generate_output_file(&fid,&sid);

  dimensions = DANU_MALLOC(int,dim);
  data_size = 1;
  for(idx=0; idx < dim; idx++) {
    dimensions[idx] = generate_random_bound_int(10,1024,&iseed);
    data_size*=dimensions[idx];
  }
  data = DANU_MALLOC(float,data_size);

  generate_random_float_data(data,data_size,&iseed);


  err = data_write_float(sid,data_name,dim, dimensions, data);
  fail_unless(H5_RETURN_OK(err), 
	      "Failed to write non-series int data");


  DANU_FREE(dimensions);
  DANU_FREE(data);

  file_delete();

}
Esempio n. 11
0
END_TEST

START_TEST(test_nsdata_exists)
{
  hid_t fid, sid;
  herr_t err;
  char data_name[] = "Data DNE";
  int exists;
  int iseed = 0x44508;
  int data;
  int size;

  generate_output_file(&fid,&sid);

  err = data_exists(sid,data_name,&exists);
  fail_unless(H5_RETURN_OK(err),
              "Failed to return success status");
  fail_unless(exists == 0,
              "Failed to return correct exists flag (F)");

  data = generate_random_int(&iseed);
  size = 1;
  data_write_int(sid,data_name,1,&size,&data);

  err = data_exists(sid,data_name,&exists);
  fail_unless(H5_RETURN_OK(err),
              "Failed to return success status");
  fail_unless(exists != 0,
              "Failed to return correct exists flag (T)");

  danu_group_close(sid);
  output_file_close(&fid);

  file_delete();

}
Esempio n. 12
0
bool _game_dive(GameData* game, int entityIndex, int depth)
{ 
  int i;
  Entity nullEntity = NULL_ENTITY; 
  FathomData* currentFathom = &game->fathoms[game->current];
  int newFathomIndex = game->current + depth;
  Entity e = currentFathom->entities[entityIndex];
  if(newFathomIndex < 0)
  {
    if(midEscape)
    {
      int numGoldenDoubloons = 0;
      for(i=0; i<MAX_INVENTORY; i++)
      {
        if(!e.inventory[i].active)
          continue;
        if(e.inventory[i].type != IT_DOUBLOON)
          continue;
        if(e.inventory[i].subtype != IST_GOLDEN)
          continue;
        numGoldenDoubloons++;
      }
      game_addGlobalMessage("%s escaped with %d golden doubloons.", _getName(e.name), numGoldenDoubloons);
      switch(numGoldenDoubloons)
      {
        case 0: game_addGlobalMessage("%s remain poor till your dying day."); break;
        case 1: game_addGlobalMessage("%s can pay off your mortgage."); break;
        case 2: game_addGlobalMessage("%s can consider early retirement."); break;
        case 3: game_addGlobalMessage("%s are independently wealthy."); break;
        case 4: game_addGlobalMessage("%s can buy a small island somewhere."); break;
        case 5: game_addGlobalMessage("%s are rich beyond your wildest dreams."); break;
      }
      currentFathom->entities[entityIndex].active = false;
      file_delete(SAVE_FILENAME);
      return true;
    } else
    {
      game_addGlobalMessage("%s are just under the surface.", _getName(e.name));
      game_addGlobalMessage("Press 'R'ise again to escape.", _getName(e.name));
      midEscape = true;
      return false;
    }
  }
  if(newFathomIndex >= MAX_FATHOMS)
  {
    game_addGlobalMessage("%s are on the bottom of the ocean.", _getName(e.name));
    return false;
  }
  currentFathom->entities[entityIndex] = nullEntity;
  int newDepth = game->current+depth;
  if(e.flags & EF_O2DEPLETES && !game_hasCharm(&e, CHARM_WATERBREATH))
  {
    Entity copy = e;
    if(game_hurt(currentFathom, &e, 10))
    {
      game_addGlobalMessage("%s drowned while %s.", _getName(copy.name), depth > 0 ? "diving" : "rising");
      return true;
    }
  }
  game_spawnAt(&game->fathoms[newDepth], e, e.pos);

  if(e.player)
  {
    file_save(SAVE_FILENAME, sizeof(GameData), game);
    for(i=0; i<MAX_ENTITIES; i++)
    {
      Entity *other = &currentFathom->entities[i];
      if(!other->active)
        continue;
      if(other->player)
        continue;
      if(!(other->flags & EF_SENTIENT))
        continue;
      if(other->flags & EF_STATIONARY)
        continue;
      if(!tilemap_visible(&currentFathom->tileMap, other->pos))
        continue;
      game_addGlobalMessage("%s follows %s %s.", _getName(other->name), _getName(e.name), depth > 0 ? "down" : "up");
      _game_dive(game, i, depth); // join in      
    }
    game->current += depth;
  }
  return true;
}
Esempio n. 13
0
/*
** Write all files from vid to the disk.  Or if vid==0 and id!=0
** write just the specific file where VFILE.ID=id.
*/
void vfile_to_disk(
  int vid,               /* vid to write to disk */
  int id,                /* Write this one file, if not zero */
  int verbose,           /* Output progress information */
  int promptFlag         /* Prompt user to confirm overwrites */
){
  Stmt q;
  Blob content;
  int nRepos = strlen(g.zLocalRoot);

  if( vid>0 && id==0 ){
    db_prepare(&q, "SELECT id, %Q || pathname, mrid, isexe, islink"
                   "  FROM vfile"
                   " WHERE vid=%d AND mrid>0",
                   g.zLocalRoot, vid);
  }else{
    assert( vid==0 && id>0 );
    db_prepare(&q, "SELECT id, %Q || pathname, mrid, isexe, islink"
                   "  FROM vfile"
                   " WHERE id=%d AND mrid>0",
                   g.zLocalRoot, id);
  }
  while( db_step(&q)==SQLITE_ROW ){
    int id, rid, isExe, isLink;
    const char *zName;

    id = db_column_int(&q, 0);
    zName = db_column_text(&q, 1);
    rid = db_column_int(&q, 2);
    isExe = db_column_int(&q, 3);
    isLink = db_column_int(&q, 4);
    content_get(rid, &content);
    if( file_is_the_same(&content, zName) ){
      blob_reset(&content);
      if( file_wd_setexe(zName, isExe) ){
        db_multi_exec("UPDATE vfile SET mtime=%lld WHERE id=%d",
                      file_wd_mtime(zName), id);
      }
      continue;
    }
    if( promptFlag && file_wd_size(zName)>=0 ){
      Blob ans;
      char *zMsg;
      char cReply;
      zMsg = mprintf("overwrite %s (a=always/y/N)? ", zName);
      prompt_user(zMsg, &ans);
      free(zMsg);
      cReply = blob_str(&ans)[0];
      blob_reset(&ans);
      if( cReply=='a' || cReply=='A' ){
        promptFlag = 0;
        cReply = 'y';
      }
      if( cReply=='n' || cReply=='N' ){
        blob_reset(&content);
        continue;
      }
    }
    if( verbose ) vcs_print("%s\n", &zName[nRepos]);
    if( file_wd_isdir(zName) == 1 ){
      /*TODO(dchest): remove directories? */
      vcs_fatal("%s is directory, cannot overwrite\n", zName);
    }    
    if( file_wd_size(zName)>=0 && (isLink || file_wd_islink(zName)) ){
      file_delete(zName);
    }
    if( isLink ){
      symlink_create(blob_str(&content), zName);
    }else{
      blob_write_to_file(&content, zName);
    }
    file_wd_setexe(zName, isExe);
    blob_reset(&content);
    db_multi_exec("UPDATE vfile SET mtime=%lld WHERE id=%d",
                  file_wd_mtime(zName), id);
  }
  db_finalize(&q);
}
Esempio n. 14
0
short file_delete_c(const char *path) {

	file_cpyname(curfilep, path, sizeof(curpath) - (curfilep - curpath));
	return(file_delete(curpath));
}
Esempio n. 15
0
static void user_menu_handler(void *data, Evas *e, Evas_Object *obj, void *event){
	Evas_Event_Key_Down *ev = (Evas_Event_Key_Down*) event;

//	if (strcmp (ev->keyname, "f") == 0)
//		ecore_evas_fullscreen_set (core.ee_core, !ecore_evas_fullscreen_get (core.ee_core));
//	else


	if (strcmp (ev->keyname, "Start") == 0){
		if(!is_download && !is_downloading && get_download_status()!=IS_DOWNLOADING)
			ecore_main_loop_quit();
	}else if (strcmp (ev->keyname, "Circle") == 0){
		if(is_main_menu);
		else if(is_asking_exit_to_xmb){
			is_asking_exit_to_xmb = false;
			is_abort = false;
			hide_edj(&download_ask);
		}else if(is_download){
			is_download = false;
			hide_obj(down);
			hide_edj(&download_perc);
			hide_edj(&download);
		}else if(is_downloading){
			is_abort = true;
	//		ecore_file_download_abort_all();
		}else if(!is_downloading && get_download_status()!=IS_DOWNLOADING){
			for(int i=0;i<Apps[category].n_elem && category !=5;i++)
				hide_obj(Applications[category].Image[i].obj);
			is_main_menu = true;
			is_drawn = category = x = y = 0;
			show_edj(&menu[0]);
			show_edj(&menu[1]);
			show_edj(&menu[2]);
			show_edj(&bar);
			app=0;
			override_text(&bar, "app_type_text", "");
			override_text(&bar, "app_version_text", "");
		}else{
			is_downloading = false;
			is_download = false;
			evas_object_resize(down, 1, Bar_Y_Val);
		}
	}else if (strcmp (ev->keyname, "Left") == 0 && !is_download) 
		x--;
	else if (strcmp (ev->keyname, "Right") == 0 && !is_download)
		x++;
	else if (strcmp (ev->keyname, "Up") == 0 && !is_download){
		if(!y)
			app-=6;
		y=!y;
	}else if (strcmp (ev->keyname, "Down") == 0 && !is_download){
		if(y)
			app+=6;
		y=!y;
	}else if (strcmp (ev->keyname, "Cross") == 0 && !is_download){
		if(is_main_menu){
			category = y*3+x;
			app = x = y = 0;
			is_drawn = 2;
			hide_edj(&menu[2]); //main menu
			if(category==5)
				hide_edj(&menu[1]); // sub menu
		}else if(is_asking_exit_to_xmb){
			is_asking_exit_to_xmb = false;
			ecore_main_loop_quit();
		}else if(app+(y*3+x) < Apps[category].n_elem){
			override_text(&download, "d_name_text", Apps[category].name[app+(y*3+x)].c_str());
			override_text(&download_perc, "d_perc_text", " ");
/*
		// uncomment this only if you have in the xml the file size (you need to edit also application.h and .cpp
			char dst[100];
			if(Apps[category].file_size[app+(y*3+x)]>1000000000)
				sprintf(dst,"%.2f Gb",1.*Apps[category].file_size[app+(y*3+x)]/1000000000);
			else if(Apps[category].file_size[app+(y*3+x)]>1000000)
				sprintf(dst,"%.2f Mb",1.*Apps[category].file_size[app+(y*3+x)]/1000000);
			else if(Apps[category].file_size[app+(y*3+x)]>1000)
				sprintf(dst,"%.2f Kb",1.*Apps[category].file_size[app+(y*3+x)]/1000);
			else
				sprintf(dst,"%d Bytes",1.*Apps[category].file_size[app+(y*3+x)]);
			override_text(&download_perc, "d_perc_text", dst);

*/
			show_edj(&download);
			show_edj(&download_perc);
			show_obj(down);
			is_download = true;
		}
		is_main_menu = false;
	}else if (strcmp (ev->keyname, "Cross") == 0 && is_download && !is_downloading){
		override_text(&download, "d_name_text", Apps[category].name[app+(y*3+x)].c_str());
		int ret = 7;
		show_obj(down);
		show_edj(&download);
		show_edj(&download_perc);
		download_status = 0;
		char dst[100];
		sprintf(dst,"%s/%s",CACHE_PATH,Apps[category].pkg_file[app+(y*3+x)].c_str());
		if(file_exist(dst))
			file_delete(dst);
		download_file(Apps[category].link[app+(y*3+x)].c_str(), dst, download_func_curl, download_is_finished);
//		ecore_file_download(Apps[category].link[app+(y*3+x)].c_str(), dst, download_is_finished, download_func, NULL, NULL);
	 	
	}
	
	if(x<0)
		x = 2;
	else if(x>2)
		x = 0;
	if(app<0)
		app=0;

	if(category != 5){
		if(is_main_menu)
			override_text(&bar, "menu_text", Categories_Names[y*3+x].c_str());
		else{
			if(app > Apps[category].n_elem-1)
				app -=6;
			override_text(&bar, "menu_text", (app+(y*3+x) < Apps[category].n_elem) ? (Apps[category].name[app+(y*3+x)].c_str()) : "" );
			override_text(&bar, "app_version_text", (app+(y*3+x) < Apps[category].n_elem) ? (Apps[category].version[app+(y*3+x)].c_str()) : "" );
			char page[20];
			sprintf(page,"%d/%d",app+(y*3+x)+1,Apps[category].n_elem);
			override_text(&menu[1], "page_of", page);
			switch(Apps[category].type_file[app+(y*3+x)]){
			 		case PSC_PACKAGE:
						override_text(&bar, "app_type_text", "Package");
			 			break;
			 		case PSC_THEME:
						override_text(&bar, "app_type_text", "Theme");
			 			break;
			 		case PSC_IMAGE:
						override_text(&bar, "app_type_text", "Image");
			 			break;
			 		case PSC_VIDEO:
						override_text(&bar, "app_type_text", "Video");
			 			break;
			 		case PSC_NO_TYPE:
						override_text(&bar, "app_type_text", " ");
			 			break;
			 		default:
						override_text(&bar, "app_type_text", " ");
			 			break;
			}
			for(int i=0;i<Apps[category].n_elem;i++)
				hide_obj(Applications[category].Image[i].obj);
			for(int i=0;i<6 && i+app < Apps[category].n_elem;i++)
				show_obj(Applications[category].Image[app+i].obj);
		}
		move_edj(&bar, Cursor_X[x], Cursor_Y[y]);
	}else{
		hide_edj(&bar);
	}
}
Esempio n. 16
0
/**
 * カレント ファイルの削除
 * @param[in] lpFilename ファイル名
 * @retval 0 成功
 * @retval -1 失敗
 */
short DOSIOCALL file_delete_c(const OEMCHAR* lpFilename)
{
	return file_delete(file_getcd(lpFilename));
}
Esempio n. 17
0
/*
** Process a single incoming HTTP request.
*/
static void win32_process_one_http_request(void *pAppData){
  HttpRequest *p = (HttpRequest*)pAppData;
  FILE *in = 0, *out = 0;
  int amt, got;
  int wanted = 0;
  char *z;
  char zRequestFName[MAX_PATH];
  char zReplyFName[MAX_PATH];
  char zCmd[2000];          /* Command-line to process the request */
  char zHdr[2000];          /* The HTTP request header */

  sqlite3_snprintf(MAX_PATH, zRequestFName,
                   "%s_in%d.txt", zTempPrefix, p->id);
  sqlite3_snprintf(MAX_PATH, zReplyFName,
                   "%s_out%d.txt", zTempPrefix, p->id);
  amt = 0;
  while( amt<sizeof(zHdr) ){
    got = recv(p->s, &zHdr[amt], sizeof(zHdr)-1-amt, 0);
    if( got==SOCKET_ERROR ) goto end_request;
    if( got==0 ){
      wanted = 0;
      break;
    }
    amt += got;
    zHdr[amt] = 0;
    z = strstr(zHdr, "\r\n\r\n");
    if( z ){
      wanted = find_content_length(zHdr) + (&z[4]-zHdr) - amt;
      break;
    }
  }
  if( amt>=sizeof(zHdr) ) goto end_request;
  out = fossil_fopen(zRequestFName, "wb");
  if( out==0 ) goto end_request;
  fwrite(zHdr, 1, amt, out);
  while( wanted>0 ){
    got = recv(p->s, zHdr, sizeof(zHdr), 0);
    if( got==SOCKET_ERROR ) goto end_request;
    if( got ){
      fwrite(zHdr, 1, got, out);
    }else{
      break;
    }
    wanted -= got;
  }
  fclose(out);
  out = 0;
  sqlite3_snprintf(sizeof(zCmd), zCmd, "\"%s\" http \"%s\" %s %s %s --nossl%s",
    g.nameOfExe, g.zRepositoryName, zRequestFName, zReplyFName,
    inet_ntoa(p->addr.sin_addr), p->zOptions
  );
  fossil_system(zCmd);
  in = fossil_fopen(zReplyFName, "rb");
  if( in ){
    while( (got = fread(zHdr, 1, sizeof(zHdr), in))>0 ){
      send(p->s, zHdr, got, 0);
    }
  }

end_request:
  if( out ) fclose(out);
  if( in ) fclose(in);
  closesocket(p->s);
  file_delete(zRequestFName);
  file_delete(zReplyFName);
  free(p);
}
Esempio n. 18
0
/**
 * Actually place an entry into the high score file
 * Return the location (0 is best) or -1 on "failure"
 */
static void highscore_write(const high_score scores[], size_t sz)
{
	size_t n;

	ang_file *lok;
	ang_file *scorefile;

	char old_name[1024];
	char cur_name[1024];
	char new_name[1024];
	char lok_name[1024];

	path_build(old_name, sizeof(old_name), ANGBAND_DIR_SCORES, "scores.old");
	path_build(cur_name, sizeof(cur_name), ANGBAND_DIR_SCORES, "scores.raw");
	path_build(new_name, sizeof(new_name), ANGBAND_DIR_SCORES, "scores.new");
	path_build(lok_name, sizeof(lok_name), ANGBAND_DIR_SCORES, "scores.lok");


	/* Read in and add new score */
	n = highscore_count(scores, sz);


	/* Lock scores */
	if (file_exists(lok_name)) {
		msg("Lock file in place for scorefile; not writing.");
		return;
	}

	safe_setuid_grab();
	lok = file_open(lok_name, MODE_WRITE, FTYPE_RAW);
	file_lock(lok);
	safe_setuid_drop();

	if (!lok) {
		msg("Failed to create lock for scorefile; not writing.");
		return;
	}


	/* Open the new file for writing */
	safe_setuid_grab();
	scorefile = file_open(new_name, MODE_WRITE, FTYPE_RAW);
	safe_setuid_drop();

	if (!scorefile) {
		msg("Failed to open new scorefile for writing.");

		file_close(lok);
		file_delete(lok_name);
		return;
	}

	file_write(scorefile, (const char *)scores, sizeof(high_score)*n);
	file_close(scorefile);

	/* Now move things around */
	safe_setuid_grab();

	if (file_exists(old_name) && !file_delete(old_name))
		msg("Couldn't delete old scorefile");

	if (file_exists(cur_name) && !file_move(cur_name, old_name))
		msg("Couldn't move old scores.raw out of the way");

	if (!file_move(new_name, cur_name))
		msg("Couldn't rename new scorefile to scores.raw");

	/* Remove the lock */
	file_close(lok);
	file_delete(lok_name);

	safe_setuid_drop();
}
Esempio n. 19
0
short DOSIOCALL file_delete_c(const OEMCHAR *path) {

	file_cpyname(curfilep, path, NELEMENTS(curpath) - (curfilep - curpath));
	return(file_delete(curpath));
}
Esempio n. 20
0
int main(int argc, char *argv[]){
	/*
	 * Here i need to get the TV resolution
	 */
	ecore_psl1ght_optimal_screen_resolution_get(&REAL_WIDTH, &REAL_HEIGHT);
	
	if(REAL_HEIGHT > 720){
		REAL_WIDTH  = 1280;
		REAL_HEIGHT = 720;
	}
	
	init_core(&core, REAL_WIDTH, REAL_HEIGHT, "Playstation Channel");
	edje_start();
	init_core_file();
	
	Cursor_Y[0] = 0.25972*REAL_HEIGHT;
	Cursor_Y[1] = 0.5445 *REAL_HEIGHT;
	
	Cursor_X[0] = 0.1*REAL_WIDTH;		// APPS      (APP 1) || MEDIA     (APP 4)
	Cursor_X[1] = 0.37421875*REAL_WIDTH;	// BMANAGERS (APP 2) || RETRO     (APP 5)
	Cursor_X[2] = 0.65*REAL_WIDTH;		// GAMES     (APP 3) || OPTIONS   (APP 6)


	
	load_edj_from_file(&core, &info, PSC_INFO_SCREEN_PATH, "information", REAL_WIDTH, REAL_HEIGHT);
	load_edj_from_file(&core, &menu[0], PSC_OPTION_MENU_PATH, "menu", REAL_WIDTH, REAL_HEIGHT); //OPTIONS
	load_edj_from_file(&core, &menu[1], PSC_SUB_MENU_PATH, "menu", REAL_WIDTH, REAL_HEIGHT);    //SUB MENU

	main_layer = evas_object_rectangle_add(get_main_object(&core));
	evas_object_resize(main_layer, REAL_WIDTH, REAL_HEIGHT);
	evas_object_color_set(main_layer, 0, 0, 0, 0);
	evas_object_show(main_layer);

	ecore_evas_object_associate(core.ee_core, main_layer, ECORE_EVAS_OBJECT_ASSOCIATE_BASE);
	override_text(&info, "information_download", " ");
	draw_edj(&info, 0, 0);

//-----------------------------------------------------------------------------------------------------

	dir_make(CACHE_PATH);
	if(file_exist(CACHE_PATH"/files.zip"))
		file_delete(CACHE_PATH"/files.zip");

	{
		char url[20];
		sprintf(url,"%s",MAINURL);
//		if(!ecore_file_download(url,CACHE_PATH"/files.zip", download_main_is_finished, download_main_func, NULL, NULL))
		download_file(url,CACHE_PATH"/files.zip", download_main_func_curl, download_main_is_finished);
		if(get_download_status()==DOWNLOAD_FAILED)
			goto end;
	}
	LoadStrings(PSC_MAIN_MENU_LANG_PATH, Categories_Names, 6);
	{
		string XML_files[5];
		LoadMainStringsFromXML(CACHE_PATH"/files.xml",XML_files);
		for(int i=0;i<5;i++){
			char tmp_char[250];
			sprintf(tmp_char,"%s/%s",CACHE_PATH,XML_files[i].c_str());
			LoadStringsFromXML(tmp_char,&Apps[i]);
			Applications[i].Image = new EFL_Image [Apps[i].n_elem];
			Applications[i].x = new int [Apps[i].n_elem];
			Applications[i].y = new int [Apps[i].n_elem];
			for(int j=0, k=0, h=0;j<Apps[i].n_elem;j++,(k>1) ? h=!h : h=h,(k>1) ? k=0 : k++ ){
				sprintf(tmp_char,"%s/%s",CACHE_PATH,Apps[i].img_file[j].c_str());
				create_image_obj(&core, &Applications[i].Image[j], tmp_char, REAL_WIDTH*0.25, REAL_HEIGHT*0.246);
				Applications[i].x[j] = Cursor_X[k];
				Applications[i].y[j] = Cursor_Y[h];
				draw_image(&Applications[i].Image[j], Applications[i].x[j], Applications[i].y[j]);
				hide_obj(Applications[i].Image[j].obj);
			}
		}
	}
//-----------------------------------------------------------------------------------------------------
	load_edj_from_file(&core, &menu[2], PSC_MAIN_MENU_PATH, "menu", REAL_WIDTH, REAL_HEIGHT);                                 //MAIN MENU
	load_edj_from_file(&core, &bar, PSC_MAIN_MENU_BAR_PATH, "main_menu_bar", REAL_WIDTH*0.25, REAL_HEIGHT*0.246);             //(Main/Sub) Menu bar
	load_edj_from_file(&core, &download, PSC_DOWNLOAD_MASK_PATH, "download_mask", REAL_WIDTH*0.3125, REAL_HEIGHT*0.3055);     //DOWNLOAD MENU

	override_text(&menu[2], "error_text", "");

	down = evas_object_rectangle_add(get_main_object(&core));
	evas_object_move(down, (REAL_WIDTH-(REAL_WIDTH*0.3125))/2 +REAL_WIDTH*0.03125,REAL_HEIGHT*0.08861 +(REAL_HEIGHT-(REAL_HEIGHT*0.3055))/2);
	Bar_X_Val = REAL_WIDTH*0.25;
	Bar_Y_Val = REAL_HEIGHT*0.058;
	evas_object_resize(down, 1, Bar_Y_Val);
	evas_object_color_set(down, 0, 0, 255, 255); //blue
	hide_obj(down);
	load_edj_from_file(&core, &download_perc, PSC_DOWNLOADPERC_MASK_PATH, "download_perc", REAL_WIDTH*0.3125, REAL_HEIGHT*0.3055);    //DOWNLOAD MENU
	load_edj_from_file(&core, &download_ask, PSC_DOWNLOAD_MASK_PATH, "download_mask_ask", REAL_WIDTH*0.3125, REAL_HEIGHT*0.3055);     //DOWNLOAD MENU ASK XMB

	ecore_event_handler_add(ECORE_EVENT_SIGNAL_EXIT, on_exit_handler, NULL);
	information_timer = ecore_timer_add(PSC_INFO_SCREEN_TIMER, delete_info, NULL);
	enable_callback(&core, main_layer, EVAS_CALLBACK_KEY_DOWN , user_menu_handler);
	
	override_text(&menu[0], "ps3_version_edit", get_ps3_version());
	char space [100];

	if(get_ps3_free_space()>1000000000)
		sprintf(space,"%ld/%ld Gigabytes",get_ps3_free_space()/1000000000,get_ps3_total_space()/1000000000);
	else if(get_ps3_free_space()>1000000)
		sprintf(space,"%ld/%ld Megabytes",get_ps3_free_space()/1000000,get_ps3_total_space()/1000000);
	else if(get_ps3_free_space()>1000)
		sprintf(space,"%ld/%ld Kilobytes",get_ps3_free_space()/1000,get_ps3_total_space()/1000);
	else
		sprintf(space,"%ld/%ld Bytes",get_ps3_free_space(),get_ps3_total_space());

	override_text(&menu[0], "ps3_hdd_free_space_edit", space);
#ifdef PSCHANNEL_VERSION
	sprintf(space,"%f",PSCHANNEL_VERSION);
	override_text(&menu[0], "software_version", space);
#else
	override_text(&menu[0], "software_version", " ");
#endif
	if(sysModuleIsLoaded(SYSMODULE_NET))
		override_text(&menu[2], "error_text", "SYSMODULE_NET NOT LOADED!!");



	start_core_loop();
	disable_callback(main_layer,EVAS_CALLBACK_KEY_DOWN, user_menu_handler);
	
end:
	dir_recursive_delete(CACHE_PATH);

	for(int i=0;i<3;i++)
		delete_edj(&menu[i]);
	for(int i=0;i<5;i++)
		for(int j=0;j<Apps[i].n_elem;j++)
			delete_obj(Applications[i].Image[j].obj);
	delete_edj(&bar);
	delete_edj(&download);
	delete_edj(&download_perc);
	delete_obj(down);


	edje_stop();
	stop_core_file();
	ecore_psl1ght_shutdown();
//	stop_core(&core);  not needed on ps3.

	if(pkg_is_installed)
		reboot_sys();
	

	return 0;
}
Esempio n. 21
0
END_TEST

START_TEST(test_nsdata_list)
{
  hid_t fid, sid;
  herr_t err;
  int iseed = 0xaa44;
  char **data_names;
  char **read_names;
  int gen_cnt, read_size, idx, num_found;
  int data;
  int size;

  generate_output_file(&fid,&sid);

  data = generate_random_int(&iseed);
  size = 1;

  gen_cnt = generate_random_bound_int(10,1024,&iseed);
  data_names = DANU_MALLOC(char *, gen_cnt);
  for(idx=0; idx < gen_cnt; idx++) {
    data_names[idx] = DANU_MALLOC(char, 32);  
    sprintf(data_names[idx], "Data Mu %04d",idx);
    data_write_int(sid,data_names[idx],1,&size,&data);
  }
  
  read_names = DANU_MALLOC(char *, gen_cnt);

  err = data_list(sid,gen_cnt,read_names,&num_found);
  fail_unless(H5_RETURN_OK(err),
              "Failed to return success status");

  fail_unless(num_found == gen_cnt,
              "Failed to find the correct number in data_list");

  fail_unless(char_array_cmp(read_names,data_names,gen_cnt) == 0,
              "Failed to read data names");

  
  DANU_FREE(read_names);
  read_size = gen_cnt / 2;
  read_names = DANU_MALLOC(char *, read_size);

  err = data_list(sid,read_size,read_names, &num_found);
  fail_unless(H5_RETURN_FAIL(err),
              "Failed to return fail status when array too small");

  fail_unless(num_found == gen_cnt,
              "Failed to find correct number in data_list");
               
  fail_unless(char_array_cmp(read_names,data_names,read_size) == 0,
              "Failed to read data names");

  

  danu_group_close(sid);
  output_file_close(&fid);

  file_delete();

}
Esempio n. 22
0
short file_delete_c(const char *path) {

	file_cpyname(curfilep, path, NELEMENTS(curpath) - (UINT)(curfilep - curpath));
	return(file_delete(curpath));
}
Esempio n. 23
0
/**
 * Processes a File Delete message from the client, 
 * performs and finalizes the operation
 *
 * @param proc_data_arg           data structure with connection parameters 
 *                                and received message
 */
void process_file_delete( PROCESS_DATA_T * proc_data ) {

  const int NOT_FOUND = -1;

  char * filename   = NULL;
  char l_msg[4096];

  char * request    = NULL;
  char * response   = NULL;

  unsigned long response_len  = 0;
  int search_filename_res     = 0;

  int result = RESULT_UNDEFINED;
  const int param_len = (proc_data->received_msg_len - HEADER_LEN - strlen(PARAM_FILENAME));

  // Copies the request to a safe buffer for searching
  request = (char*)malloc(sizeof(char) * proc_data->received_msg_len + 1);
  memcpy(request, proc_data->received_message, proc_data->received_msg_len);
  request[proc_data->received_msg_len] = '\0';

  // Gets name of file to delete
  search_filename_res = STR_SEARCH( proc_data->received_message, PARAM_FILENAME, HEADER_LEN);
  if ( search_filename_res == NOT_FOUND ) {

    result = RESULT_INVALID_REQUEST;
    goto END_PROCESS_FILE_DELETE;
  }

  filename = (char*)malloc(sizeof(char) * proc_data->received_msg_len);
  memcpy( filename, &(request[ ( search_filename_res + strlen(PARAM_FILENAME) ) ]), param_len );
  filename[param_len] = '\0';
  
  sprintf(l_msg, "A request has been received to delete the file: %s", filename);
  LOGGER(__FUNCTION__, l_msg);
  
  if (file_exists(filename) == TRUE) {
  
    if (file_delete(filename) == TRUE) {
    
      result = RESULT_SUCCESS;
    }
    else {
      result = RESULT_FILE_DELETE_ERROR;
    }    
  }
  else {
    result = RESULT_FILE_NOT_FOUND;
  }
    
  // Generates response message
  response = message_file_delete_response( result, &response_len );  

  // Sends response message
  if ( !process_outgoing_message( proc_data->connection, response, response_len ) ) {
    
    LOGGER(__FUNCTION__, "File Receive response message could not be sent.");
  }

END_PROCESS_FILE_DELETE:

  // Cleanup
  if (request != NULL) {
    free(request);
  }
  if (response != NULL) {
    free(response);
  }
  if (filename != NULL) {
    free(filename);
  }

  return;
}
Esempio n. 24
0
short file_delete_c(const char *path) {

	*curfilep = '\0';
	file_catname(curpath, path, sizeof(curpath));
	return(file_delete(curpath));
}
Esempio n. 25
0
/*
** Start a listening socket and process incoming HTTP requests on
** that socket.
*/
void win32_http_server(
  int mnPort, int mxPort,   /* Range of allowed TCP port numbers */
  const char *zBrowser,     /* Command to launch browser.  (Or NULL) */
  const char *zStopper,     /* Stop server when this file is exists (Or NULL) */
  const char *zNotFound,    /* The --notfound option, or NULL */
  int flags                 /* One or more HTTP_SERVER_ flags */
){
  WSADATA wd;
  SOCKET s = INVALID_SOCKET;
  SOCKADDR_IN addr;
  int idCnt = 0;
  int iPort = mnPort;
  Blob options;
  WCHAR zTmpPath[MAX_PATH];

  if( zStopper ) file_delete(zStopper);
  blob_zero(&options);
  if( zNotFound ){
    blob_appendf(&options, " --notfound %s", zNotFound);
  }
  if( g.useLocalauth ){
    blob_appendf(&options, " --localauth");
  }
  if( WSAStartup(MAKEWORD(1,1), &wd) ){
    fossil_fatal("unable to initialize winsock");
  }
  while( iPort<=mxPort ){
    s = socket(AF_INET, SOCK_STREAM, 0);
    if( s==INVALID_SOCKET ){
      fossil_fatal("unable to create a socket");
    }
    addr.sin_family = AF_INET;
    addr.sin_port = htons(iPort);
    if( flags & HTTP_SERVER_LOCALHOST ){
      addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
    }else{
      addr.sin_addr.s_addr = htonl(INADDR_ANY);
    }
    if( bind(s, (struct sockaddr*)&addr, sizeof(addr))==SOCKET_ERROR ){
      closesocket(s);
      iPort++;
      continue;
    }
    if( listen(s, SOMAXCONN)==SOCKET_ERROR ){
      closesocket(s);
      iPort++;
      continue;
    }
    break;
  }
  if( iPort>mxPort ){
    if( mnPort==mxPort ){
      fossil_fatal("unable to open listening socket on ports %d", mnPort);
    }else{
      fossil_fatal("unable to open listening socket on any"
                   " port in the range %d..%d", mnPort, mxPort);
    }
  }
  if( !GetTempPathW(MAX_PATH, zTmpPath) ){
    fossil_fatal("unable to get path to the temporary directory.");
  }
  zTempPrefix = mprintf("%sfossil_server_P%d_", fossil_unicode_to_utf8(zTmpPath), iPort);
  fossil_print("Listening for HTTP requests on TCP port %d\n", iPort);
  if( zBrowser ){
    zBrowser = mprintf(zBrowser, iPort);
    fossil_print("Launch webbrowser: %s\n", zBrowser);
    fossil_system(zBrowser);
  }
  fossil_print("Type Ctrl-C to stop the HTTP server\n");
  /* Set the service status to running and pass the listener socket to the
  ** service handling procedures. */
  win32_http_service_running(s);
  for(;;){
    SOCKET client;
    SOCKADDR_IN client_addr;
    HttpRequest *p;
    int len = sizeof(client_addr);
    int wsaError;

    client = accept(s, (struct sockaddr*)&client_addr, &len);
    if( client==INVALID_SOCKET ){
      /* If the service control handler has closed the listener socket,
      ** cleanup and return, otherwise report a fatal error. */
      wsaError =  WSAGetLastError();
      if( (wsaError==WSAEINTR) || (wsaError==WSAENOTSOCK) ){
        WSACleanup();
        return;
      }else{
        closesocket(s);
        WSACleanup();
        fossil_fatal("error from accept()");
      }
    }else if( zStopper && file_size(zStopper)>=0 ){
      break;
    }
    p = fossil_malloc( sizeof(*p) );
    p->id = ++idCnt;
    p->s = client;
    p->addr = client_addr;
    p->zOptions = blob_str(&options);
    _beginthread(win32_process_one_http_request, 0, (void*)p);
  }
  closesocket(s);
  WSACleanup();
}
Esempio n. 26
0
void qlevel_save(STRING *filename)
{
	STRING *file = "#256";
	make_path(file, filename);
	
	STRING *backup = "#256";
	str_cpy(backup, file);
	str_cat(backup, ".bak");
	file_delete(backup);
	file_rename(file, backup);
	
	ini_write_int(file, "Level Information", "EntityCount", 0);
	ini_write_int(file, "Level Information", "LightCount", 0);
	ini_write_int(file, "Level Information", "FogCount", 0);
	
	int countEntity = 0;
	int countLight = 0;
	int countFog = 0;
	
	STRING *section = "#64";
	for(you = ent_next(NULL); you != NULL; you = ent_next(you))
	{
		switch(you->group)
		{
			case GROUP_LEVEL:
				str_cpy(section, "Entity ");
				str_cat(section, str_for_int(NULL, countEntity));
				
				ini_write_string(file, section, "Model", you->type);
				ini_write_int(file, section, "ActionCount", 0);
				int actionCount = 0;
				STRING *actionName = "#64";
				ActionInformation *entry;
				for(entry = list_first(you->string1); entry != NULL; entry = list_next(you->string1, entry))
				{
					str_cpy(actionName, "Action");
					str_cat(actionName, str_for_int(NULL, actionCount));
					ini_write_string(file, section, actionName, _str(entry->actionname));
					actionCount++;
				}
				ini_write_int(file, section, "ActionCount", actionCount);
				
				ini_write_float(file, section, "X", you->x);
				ini_write_float(file, section, "Y", you->y);
				ini_write_float(file, section, "Z", you->z);
				ini_write_float(file, section, "Pan", cycle(you->pan, 0, 360));
				ini_write_float(file, section, "Tilt", cycle(you->tilt, 0, 360));
				ini_write_float(file, section, "Roll", cycle(you->roll, 0, 360));
				ini_write_float(file, section, "ScaleX", you->scale_x);
				ini_write_float(file, section, "ScaleY", you->scale_y);
				ini_write_float(file, section, "ScaleZ", you->scale_z);
				ini_write_float(file, section, "Lightrange", you->lightrange);

				countEntity++;
				break;
		}
	}
	
	ini_write_int(file, "Level Information", "EntityCount", countEntity);
	ini_write_int(file, "Level Information", "LightCount", countLight);
	ini_write_int(file, "Level Information", "FogCount", countFog);
}
Esempio n. 27
0
/*
 * Remove old lines from pref files
 *
 * If you are using setgid, make sure privileges were raised prior
 * to calling this.
 */
static void remove_old_dump(const char *cur_fname, const char *mark)
{
	bool between_marks = FALSE;
	bool changed = FALSE;

	char buf[1024];

	char start_line[1024];
	char end_line[1024];

	char new_fname[1024];

	ang_file *new_file;
	ang_file *cur_file;


	/* Format up some filenames */
	strnfmt(new_fname, sizeof(new_fname), "%s.new", cur_fname);

	/* Work out what we expect to find */
	strnfmt(start_line, sizeof(start_line), "%s begin %s",
			dump_separator, mark);
	strnfmt(end_line, sizeof(end_line), "%s end %s", dump_separator, mark);



	/* Open current file */
	cur_file = file_open(cur_fname, MODE_READ, -1);
	if (!cur_file)
		return;

	/* Open new file */
	new_file = file_open(new_fname, MODE_WRITE, FTYPE_TEXT);
	if (!new_file) {
		msg("Failed to create file %s", new_fname);
		return;
	}

	/* Loop for every line */
	while (file_getl(cur_file, buf, sizeof(buf))) {
		/* If we find the start line, turn on */
		if (!strcmp(buf, start_line)) {
			between_marks = TRUE;
		}

		/* If we find the finish line, turn off */
		else if (!strcmp(buf, end_line)) {
			between_marks = FALSE;
			changed = TRUE;
		}

		if (!between_marks) {
			/* Copy orginal line */
			file_putf(new_file, "%s\n", buf);
		}
	}

	/* Close files */
	file_close(cur_file);
	file_close(new_file);

	/* If there are changes, move things around */
	if (changed) {
		char old_fname[1024];
		strnfmt(old_fname, sizeof(old_fname), "%s.old", cur_fname);

		if (file_move(cur_fname, old_fname)) {
			file_move(new_fname, cur_fname);
			file_delete(old_fname);
		}
	}

	/* Otherwise just destroy the new file */
	else {
		file_delete(new_fname);
	}
}
Esempio n. 28
0
/*
 * Attempt to save the player in a savefile
 */
bool savefile_save(const char *path)
{
	ang_file *file;

	char new_savefile[1024];
	char old_savefile[1024];

	/* New savefile */
	strnfmt(new_savefile, sizeof(new_savefile), "%s.new", path);
	strnfmt(old_savefile, sizeof(old_savefile), "%s.old", path);

	/* Make sure that the savefile doesn't already exist */
	safe_setuid_grab();
	file_delete(new_savefile);
	file_delete(old_savefile);
	safe_setuid_drop();

	/* Open the savefile */
	safe_setuid_grab();
	file = file_open(new_savefile, MODE_WRITE, FTYPE_SAVE);
	safe_setuid_drop();
	
	if (file)
	{
		file_write(file, (char *) &savefile_magic, 4);
		file_write(file, (char *) &savefile_name, 4);

		character_saved = try_save(file);
		file_close(file);
	}

	if (character_saved)
	{
		bool err = FALSE;

		safe_setuid_grab();

		if (file_exists(savefile) && !file_move(savefile, old_savefile))
			err = TRUE;

		if (!err)
		{
			if (!file_move(new_savefile, savefile))
				err = TRUE;

			if (err)
				file_move(old_savefile, savefile);
			else
				file_delete(old_savefile);
		}

		safe_setuid_drop();

		return err ? FALSE : TRUE;
	}
	
	/* Delete temp file */
	safe_setuid_grab();
	file_delete(new_savefile);
	safe_setuid_drop();

	return FALSE;
}
Esempio n. 29
0
/*
 * Attempt to save the player in a savefile
 */
bool savefile_save(const char *path)
{
	ang_file *file;
	int count = 0;
	char new_savefile[1024];
	char old_savefile[1024];

	/* New savefile */
	strnfmt(old_savefile, sizeof(old_savefile), "%s%u.old", path,Rand_simple(1000000));
	while (file_exists(old_savefile) && (count++ < 100)) {
		strnfmt(old_savefile, sizeof(old_savefile), "%s%u%u.old", path,Rand_simple(1000000),count);
	}
	count = 0;
	/* Make sure that the savefile doesn't already exist */
	/*safe_setuid_grab();
	file_delete(new_savefile);
	file_delete(old_savefile);
	safe_setuid_drop();*/

	/* Open the savefile */
	safe_setuid_grab();
	strnfmt(new_savefile, sizeof(new_savefile), "%s%u.new", path,Rand_simple(1000000));
	while (file_exists(new_savefile) && (count++ < 100)) {
		strnfmt(new_savefile, sizeof(new_savefile), "%s%u%u.new", path,Rand_simple(1000000),count);
	}
	file = file_open(new_savefile, MODE_WRITE, FTYPE_SAVE);
	safe_setuid_drop();

	if (file)
	{
		file_write(file, (char *) &savefile_magic, 4);
		file_write(file, (char *) &savefile_name, 4);

		character_saved = try_save(file);
		file_close(file);
	}

	if (character_saved)
	{
		bool err = FALSE;

		safe_setuid_grab();

		if (file_exists(savefile) && !file_move(savefile, old_savefile))
			err = TRUE;

		if (!err)
		{
			if (!file_move(new_savefile, savefile))
				err = TRUE;

			if (err)
				file_move(old_savefile, savefile);
			else
				file_delete(old_savefile);
		} 

		safe_setuid_drop();

		return err ? FALSE : TRUE;
	}

	/* Delete temp file if the save failed */
	if (file)
	{
		/* file is no longer valid, but it still points to a non zero
		 * value if the file was created above */
		safe_setuid_grab();
		file_delete(new_savefile);
		safe_setuid_drop();
	}
	return FALSE;
}
Esempio n. 30
0
/*
** COMMAND: merge
**
** Usage: %fossil merge ?OPTIONS? ?VERSION?
**
** The argument VERSION is a version that should be merged into the
** current checkout.  All changes from VERSION back to the nearest
** common ancestor are merged.  Except, if either of the --cherrypick or
** --backout options are used only the changes associated with the
** single check-in VERSION are merged.  The --backout option causes
** the changes associated with VERSION to be removed from the current
** checkout rather than added.
**
** If the VERSION argument is omitted, then Fossil attempts to find
** a recent fork on the current branch to merge.
**
** Only file content is merged.  The result continues to use the
** file and directory names from the current checkout even if those
** names might have been changed in the branch being merged in.
**
** Other options:
**
**   --baseline BASELINE     Use BASELINE as the "pivot" of the merge instead
**                           of the nearest common ancestor.  This allows
**                           a sequence of changes in a branch to be merged
**                           without having to merge the entire branch.
**
**   --binary GLOBPATTERN    Treat files that match GLOBPATTERN as binary
**                           and do not try to merge parallel changes.  This
**                           option overrides the "binary-glob" setting.
**
**   --case-sensitive BOOL   Override the case-sensitive setting.  If false,
**                           files whose names differ only in case are taken
**                           to be the same file.
**
**   -f|--force              Force the merge even if it would be a no-op.
**
**   --force-missing         Force the merge even if there is missing content.
**
**   --integrate             Merged branch will be closed when committing.
**
**   -n|--dry-run            If given, display instead of run actions
**
**   -v|--verbose            Show additional details of the merge
*/
void merge_cmd(void){
  int vid;              /* Current version "V" */
  int mid;              /* Version we are merging from "M" */
  int pid;              /* The pivot version - most recent common ancestor P */
  int verboseFlag;      /* True if the -v|--verbose option is present */
  int integrateFlag;    /* True if the --integrate option is present */
  int pickFlag;         /* True if the --cherrypick option is present */
  int backoutFlag;      /* True if the --backout option is present */
  int dryRunFlag;       /* True if the --dry-run or -n option is present */
  int forceFlag;        /* True if the --force or -f option is present */
  int forceMissingFlag; /* True if the --force-missing option is present */
  const char *zBinGlob; /* The value of --binary */
  const char *zPivot;   /* The value of --baseline */
  int debugFlag;        /* True if --debug is present */
  int nChng;            /* Number of file name changes */
  int *aChng;           /* An array of file name changes */
  int i;                /* Loop counter */
  int nConflict = 0;    /* Number of conflicts seen */
  int nOverwrite = 0;   /* Number of unmanaged files overwritten */
  Stmt q;


  /* Notation:
  **
  **      V     The current checkout
  **      M     The version being merged in
  **      P     The "pivot" - the most recent common ancestor of V and M.
  */

  undo_capture_command_line();
  verboseFlag = find_option("verbose","v",0)!=0;
  forceMissingFlag = find_option("force-missing",0,0)!=0;
  if( !verboseFlag ){
    verboseFlag = find_option("detail",0,0)!=0; /* deprecated */
  }
  pickFlag = find_option("cherrypick",0,0)!=0;
  integrateFlag = find_option("integrate",0,0)!=0;
  backoutFlag = find_option("backout",0,0)!=0;
  debugFlag = find_option("debug",0,0)!=0;
  zBinGlob = find_option("binary",0,1);
  dryRunFlag = find_option("dry-run","n",0)!=0;
  if( !dryRunFlag ){
    dryRunFlag = find_option("nochange",0,0)!=0; /* deprecated */
  }
  forceFlag = find_option("force","f",0)!=0;
  zPivot = find_option("baseline",0,1);
  verify_all_options();
  db_must_be_within_tree();
  if( zBinGlob==0 ) zBinGlob = db_get("binary-glob",0);
  vid = db_lget_int("checkout", 0);
  if( vid==0 ){
    fossil_fatal("nothing is checked out");
  }

  /* Find mid, the artifactID of the version to be merged into the current
  ** check-out */
  if( g.argc==3 ){
    /* Mid is specified as an argument on the command-line */
    mid = name_to_typed_rid(g.argv[2], "ci");
    if( mid==0 || !is_a_version(mid) ){
      fossil_fatal("not a version: %s", g.argv[2]);
    }
  }else if( g.argc==2 ){
    /* No version specified on the command-line so pick the most recent
    ** leaf that is (1) not the version currently checked out and (2)
    ** has not already been merged into the current checkout and (3)
    ** the leaf is not closed and (4) the leaf is in the same branch
    ** as the current checkout.
    */
    Stmt q;
    if( pickFlag || backoutFlag || integrateFlag){
      fossil_fatal("cannot use --backout, --cherrypick or --integrate with a fork merge");
    }
    mid = db_int(0,
      "SELECT leaf.rid"
      "  FROM leaf, event"
      " WHERE leaf.rid=event.objid"
      "   AND leaf.rid!=%d"                                /* Constraint (1) */
      "   AND leaf.rid NOT IN (SELECT merge FROM vmerge)"  /* Constraint (2) */
      "   AND NOT EXISTS(SELECT 1 FROM tagxref"            /* Constraint (3) */
                    "     WHERE rid=leaf.rid"
                    "       AND tagid=%d"
                    "       AND tagtype>0)"
      "   AND (SELECT value FROM tagxref"                  /* Constraint (4) */
            "   WHERE tagid=%d AND rid=%d AND tagtype>0) ="
            " (SELECT value FROM tagxref"
            "   WHERE tagid=%d AND rid=leaf.rid AND tagtype>0)"
      " ORDER BY event.mtime DESC LIMIT 1",
      vid, TAG_CLOSED, TAG_BRANCH, vid, TAG_BRANCH
    );
    if( mid==0 ){
      fossil_fatal("no unmerged forks of branch \"%s\"",
        db_text(0, "SELECT value FROM tagxref"
                   " WHERE tagid=%d AND rid=%d AND tagtype>0",
                   TAG_BRANCH, vid)
      );
    }
    db_prepare(&q,
      "SELECT blob.uuid,"
          "   datetime(event.mtime%s),"
          "   coalesce(ecomment, comment),"
          "   coalesce(euser, user)"
      "  FROM event, blob"
      " WHERE event.objid=%d AND blob.rid=%d",
      timeline_utc(), mid, mid
    );
    if( db_step(&q)==SQLITE_ROW ){
      char *zCom = mprintf("Merging fork [%S] at %s by %s: \"%s\"",
            db_column_text(&q, 0), db_column_text(&q, 1),
            db_column_text(&q, 3), db_column_text(&q, 2));
      comment_print(zCom, db_column_text(&q,2), 0, -1, g.comFmtFlags);
      fossil_free(zCom);
    }
    db_finalize(&q);
  }else{
    usage("?OPTIONS? ?VERSION?");
    return;
  }

  if( zPivot ){
    pid = name_to_typed_rid(zPivot, "ci");
    if( pid==0 || !is_a_version(pid) ){
      fossil_fatal("not a version: %s", zPivot);
    }
    if( pickFlag ){
      fossil_fatal("incompatible options: --cherrypick & --baseline");
    }
  }else if( pickFlag || backoutFlag ){
    if( integrateFlag ){
      fossil_fatal("incompatible options: --integrate & --cherrypick or --backout");
    }
    pid = db_int(0, "SELECT pid FROM plink WHERE cid=%d AND isprim", mid);
    if( pid<=0 ){
      fossil_fatal("cannot find an ancestor for %s", g.argv[2]);
    }
  }else{
    pivot_set_primary(mid);
    pivot_set_secondary(vid);
    db_prepare(&q, "SELECT merge FROM vmerge WHERE id=0");
    while( db_step(&q)==SQLITE_ROW ){
      pivot_set_secondary(db_column_int(&q,0));
    }
    db_finalize(&q);
    pid = pivot_find();
    if( pid<=0 ){
      fossil_fatal("cannot find a common ancestor between the current "
                   "checkout and %s", g.argv[2]);
    }
  }
  if( backoutFlag ){
    int t = pid;
    pid = mid;
    mid = t;
  }
  if( !is_a_version(pid) ){
    fossil_fatal("not a version: record #%d", pid);
  }
  if( !forceFlag && mid==pid ){
    fossil_print("Merge skipped because it is a no-op. "
                 " Use --force to override.\n");
    return;
  }
  if( integrateFlag && !is_a_leaf(mid)){
    fossil_warning("ignoring --integrate: %s is not a leaf", g.argv[2]);
    integrateFlag = 0;
  }
  if( verboseFlag ){
    print_checkin_description(mid, 12, integrateFlag?"integrate:":"merge-from:");
    print_checkin_description(pid, 12, "baseline:");
  }
  vfile_check_signature(vid, CKSIG_ENOTFILE);
  db_begin_transaction();
  if( !dryRunFlag ) undo_begin();
  if( load_vfile_from_rid(mid) && !forceMissingFlag ){
    fossil_fatal("missing content, unable to merge");
  }
  if( load_vfile_from_rid(pid) && !forceMissingFlag ){
    fossil_fatal("missing content, unable to merge");
  }
  if( debugFlag ){
    char *z;
    z = db_text(0, "SELECT uuid FROM blob WHERE rid=%d", pid);
    fossil_print("P=%d %z\n", pid, z);
    z = db_text(0, "SELECT uuid FROM blob WHERE rid=%d", mid);
    fossil_print("M=%d %z\n", mid, z);
    z = db_text(0, "SELECT uuid FROM blob WHERE rid=%d", vid);
    fossil_print("V=%d %z\n", vid, z);
  }

  /*
  ** The vfile.pathname field is used to match files against each other.  The
  ** FV table contains one row for each each unique filename in
  ** in the current checkout, the pivot, and the version being merged.
  */
  db_multi_exec(
    "DROP TABLE IF EXISTS fv;"
    "CREATE TEMP TABLE fv("
    "  fn TEXT PRIMARY KEY %s,"   /* The filename */
    "  idv INTEGER,"              /* VFILE entry for current version */
    "  idp INTEGER,"              /* VFILE entry for the pivot */
    "  idm INTEGER,"              /* VFILE entry for version merging in */
    "  chnged BOOLEAN,"           /* True if current version has been edited */
    "  ridv INTEGER,"             /* Record ID for current version */
    "  ridp INTEGER,"             /* Record ID for pivot */
    "  ridm INTEGER,"             /* Record ID for merge */
    "  isexe BOOLEAN,"            /* Execute permission enabled */
    "  fnp TEXT %s,"              /* The filename in the pivot */
    "  fnm TEXT %s,"              /* the filename in the merged version */
    "  islinkv BOOLEAN,"          /* True if current version is a symlink */
    "  islinkm BOOLEAN"           /* True if merged version in is a symlink */
    ");",
    filename_collation(), filename_collation(), filename_collation()
  );

  /* Add files found in V
  */
  db_multi_exec(
    "INSERT OR IGNORE"
    " INTO fv(fn,fnp,fnm,idv,idp,idm,ridv,ridp,ridm,isexe,chnged)"
    " SELECT pathname, pathname, pathname, id, 0, 0, rid, 0, 0, isexe, chnged "
    " FROM vfile WHERE vid=%d",
    vid
  );

  /*
  ** Compute name changes from P->V
  */
  find_filename_changes(pid, vid, 0, &nChng, &aChng, debugFlag ? "P->V" : 0);
  if( nChng ){
    for(i=0; i<nChng; i++){
      char *z;
      z = db_text(0, "SELECT name FROM filename WHERE fnid=%d", aChng[i*2]);
      db_multi_exec(
        "UPDATE fv SET fnp=%Q, fnm=%Q"
        " WHERE fn=(SELECT name FROM filename WHERE fnid=%d)",
        z, z, aChng[i*2+1]
      );
      free(z);
    }
    fossil_free(aChng);
    db_multi_exec("UPDATE fv SET fnm=fnp WHERE fnp!=fn");
  }

  /* Add files found in P but not in V
  */
  db_multi_exec(
    "INSERT OR IGNORE"
    " INTO fv(fn,fnp,fnm,idv,idp,idm,ridv,ridp,ridm,isexe,chnged)"
    " SELECT pathname, pathname, pathname, 0, 0, 0, 0, 0, 0, isexe, 0 "
    "   FROM vfile"
    "  WHERE vid=%d AND pathname %s NOT IN (SELECT fnp FROM fv)",
    pid, filename_collation()
  );

  /*
  ** Compute name changes from P->M
  */
  find_filename_changes(pid, mid, 0, &nChng, &aChng, debugFlag ? "P->M" : 0);
  if( nChng ){
    if( nChng>4 ) db_multi_exec("CREATE INDEX fv_fnp ON fv(fnp)");
    for(i=0; i<nChng; i++){
      db_multi_exec(
        "UPDATE fv SET fnm=(SELECT name FROM filename WHERE fnid=%d)"
        " WHERE fnp=(SELECT name FROM filename WHERE fnid=%d)",
        aChng[i*2+1], aChng[i*2]
      );
    }
    fossil_free(aChng);
  }

  /* Add files found in M but not in P or V.
  */
  db_multi_exec(
    "INSERT OR IGNORE"
    " INTO fv(fn,fnp,fnm,idv,idp,idm,ridv,ridp,ridm,isexe,chnged)"
    " SELECT pathname, pathname, pathname, 0, 0, 0, 0, 0, 0, isexe, 0 "
    "   FROM vfile"
    "  WHERE vid=%d"
    "    AND pathname %s NOT IN (SELECT fnp FROM fv UNION SELECT fnm FROM fv)",
    mid, filename_collation()
  );

  /*
  ** Compute the file version ids for P and M.
  */
  db_multi_exec(
    "UPDATE fv SET"
    " idp=coalesce((SELECT id FROM vfile WHERE vid=%d AND fnp=pathname),0),"
    " ridp=coalesce((SELECT rid FROM vfile WHERE vid=%d AND fnp=pathname),0),"
    " idm=coalesce((SELECT id FROM vfile WHERE vid=%d AND fnm=pathname),0),"
    " ridm=coalesce((SELECT rid FROM vfile WHERE vid=%d AND fnm=pathname),0),"
    " islinkv=coalesce((SELECT islink FROM vfile"
                    " WHERE vid=%d AND fnm=pathname),0),"
    " islinkm=coalesce((SELECT islink FROM vfile"
                    " WHERE vid=%d AND fnm=pathname),0)",
    pid, pid, mid, mid, vid, mid
  );

  if( debugFlag ){
    db_prepare(&q,
       "SELECT rowid, fn, fnp, fnm, chnged, ridv, ridp, ridm, "
       "       isexe, islinkv, islinkm FROM fv"
    );
    while( db_step(&q)==SQLITE_ROW ){
       fossil_print("%3d: ridv=%-4d ridp=%-4d ridm=%-4d chnged=%d isexe=%d "
                    " islinkv=%d islinkm=%d\n",
          db_column_int(&q, 0),
          db_column_int(&q, 5),
          db_column_int(&q, 6),
          db_column_int(&q, 7),
          db_column_int(&q, 4),
          db_column_int(&q, 8),
          db_column_int(&q, 9),
          db_column_int(&q, 10));
       fossil_print("     fn  = [%s]\n", db_column_text(&q, 1));
       fossil_print("     fnp = [%s]\n", db_column_text(&q, 2));
       fossil_print("     fnm = [%s]\n", db_column_text(&q, 3));
    }
    db_finalize(&q);
  }

  /*
  ** Find files in M and V but not in P and report conflicts.
  ** The file in M will be ignored.  It will be treated as if it
  ** does not exist.
  */
  db_prepare(&q,
    "SELECT idm FROM fv WHERE idp=0 AND idv>0 AND idm>0"
  );
  while( db_step(&q)==SQLITE_ROW ){
    int idm = db_column_int(&q, 0);
    char *zName = db_text(0, "SELECT pathname FROM vfile WHERE id=%d", idm);
    fossil_warning("WARNING - no common ancestor: %s", zName);
    free(zName);
    db_multi_exec("UPDATE fv SET idm=0 WHERE idm=%d", idm);
  }
  db_finalize(&q);

  /*
  ** Add to V files that are not in V or P but are in M
  */
  db_prepare(&q,
    "SELECT idm, rowid, fnm FROM fv AS x"
    " WHERE idp=0 AND idv=0 AND idm>0"
  );
  while( db_step(&q)==SQLITE_ROW ){
    int idm = db_column_int(&q, 0);
    int rowid = db_column_int(&q, 1);
    int idv;
    const char *zName;
    char *zFullName;
    db_multi_exec(
      "INSERT INTO vfile(vid,chnged,deleted,rid,mrid,isexe,islink,pathname)"
      "  SELECT %d,%d,0,rid,mrid,isexe,islink,pathname FROM vfile WHERE id=%d",
      vid, integrateFlag?5:3, idm
    );
    idv = db_last_insert_rowid();
    db_multi_exec("UPDATE fv SET idv=%d WHERE rowid=%d", idv, rowid);
    zName = db_column_text(&q, 2);
    zFullName = mprintf("%s%s", g.zLocalRoot, zName);
    if( file_wd_isfile_or_link(zFullName) ){
      fossil_print("ADDED %s (overwrites an unmanaged file)\n", zName);
      nOverwrite++;
    }else{
      fossil_print("ADDED %s\n", zName);
    }
    fossil_free(zFullName);
    if( !dryRunFlag ){
      undo_save(zName);
      vfile_to_disk(0, idm, 0, 0);
    }
  }
  db_finalize(&q);

  /*
  ** Find files that have changed from P->M but not P->V.
  ** Copy the M content over into V.
  */
  db_prepare(&q,
    "SELECT idv, ridm, fn, islinkm FROM fv"
    " WHERE idp>0 AND idv>0 AND idm>0"
    "   AND ridm!=ridp AND ridv=ridp AND NOT chnged"
  );
  while( db_step(&q)==SQLITE_ROW ){
    int idv = db_column_int(&q, 0);
    int ridm = db_column_int(&q, 1);
    const char *zName = db_column_text(&q, 2);
    int islinkm = db_column_int(&q, 3);
    /* Copy content from idm over into idv.  Overwrite idv. */
    fossil_print("UPDATE %s\n", zName);
    if( !dryRunFlag ){
      undo_save(zName);
      db_multi_exec(
        "UPDATE vfile SET mtime=0, mrid=%d, chnged=%d, islink=%d "
        " WHERE id=%d", ridm, integrateFlag?4:2, islinkm, idv
      );
      vfile_to_disk(0, idv, 0, 0);
    }
  }
  db_finalize(&q);

  /*
  ** Do a three-way merge on files that have changes on both P->M and P->V.
  */
  db_prepare(&q,
    "SELECT ridm, idv, ridp, ridv, %s, fn, isexe, islinkv, islinkm FROM fv"
    " WHERE idp>0 AND idv>0 AND idm>0"
    "   AND ridm!=ridp AND (ridv!=ridp OR chnged)",
    glob_expr("fv.fn", zBinGlob)
  );
  while( db_step(&q)==SQLITE_ROW ){
    int ridm = db_column_int(&q, 0);
    int idv = db_column_int(&q, 1);
    int ridp = db_column_int(&q, 2);
    int ridv = db_column_int(&q, 3);
    int isBinary = db_column_int(&q, 4);
    const char *zName = db_column_text(&q, 5);
    int isExe = db_column_int(&q, 6);
    int islinkv = db_column_int(&q, 7);
    int islinkm = db_column_int(&q, 8);
    int rc;
    char *zFullPath;
    Blob m, p, r;
    /* Do a 3-way merge of idp->idm into idp->idv.  The results go into idv. */
    if( verboseFlag ){
      fossil_print("MERGE %s  (pivot=%d v1=%d v2=%d)\n",
                   zName, ridp, ridm, ridv);
    }else{
      fossil_print("MERGE %s\n", zName);
    }
    if( islinkv || islinkm /* || file_wd_islink(zFullPath) */ ){
      fossil_print("***** Cannot merge symlink %s\n", zName);
      nConflict++;
    }else{
      undo_save(zName);
      zFullPath = mprintf("%s/%s", g.zLocalRoot, zName);
      content_get(ridp, &p);
      content_get(ridm, &m);
      if( isBinary ){
        rc = -1;
        blob_zero(&r);
      }else{
        unsigned mergeFlags = dryRunFlag ? MERGE_DRYRUN : 0;
        rc = merge_3way(&p, zFullPath, &m, &r, mergeFlags);
      }
      if( rc>=0 ){
        if( !dryRunFlag ){
          blob_write_to_file(&r, zFullPath);
          file_wd_setexe(zFullPath, isExe);
        }
        db_multi_exec("UPDATE vfile SET mtime=0 WHERE id=%d", idv);
        if( rc>0 ){
          fossil_print("***** %d merge conflicts in %s\n", rc, zName);
          nConflict++;
        }
      }else{
        fossil_print("***** Cannot merge binary file %s\n", zName);
        nConflict++;
      }
      blob_reset(&p);
      blob_reset(&m);
      blob_reset(&r);
    }
    db_multi_exec("INSERT OR IGNORE INTO vmerge(id,merge) VALUES(%d,%d)",
                  idv,ridm);
  }
  db_finalize(&q);

  /*
  ** Drop files that are in P and V but not in M
  */
  db_prepare(&q,
    "SELECT idv, fn, chnged FROM fv"
    " WHERE idp>0 AND idv>0 AND idm=0"
  );
  while( db_step(&q)==SQLITE_ROW ){
    int idv = db_column_int(&q, 0);
    const char *zName = db_column_text(&q, 1);
    int chnged = db_column_int(&q, 2);
    /* Delete the file idv */
    fossil_print("DELETE %s\n", zName);
    if( chnged ){
      fossil_warning("WARNING: local edits lost for %s\n", zName);
      nConflict++;
    }
    undo_save(zName);
    db_multi_exec(
      "UPDATE vfile SET deleted=1 WHERE id=%d", idv
    );
    if( !dryRunFlag ){
      char *zFullPath = mprintf("%s%s", g.zLocalRoot, zName);
      file_delete(zFullPath);
      free(zFullPath);
    }
  }
  db_finalize(&q);

  /*
  ** Rename files that have taken a rename on P->M but which keep the same
  ** name o P->V.   If a file is renamed on P->V only or on both P->V and
  ** P->M then we retain the V name of the file.
  */
  db_prepare(&q,
    "SELECT idv, fnp, fnm FROM fv"
    " WHERE idv>0 AND idp>0 AND idm>0 AND fnp=fn AND fnm!=fnp"
  );
  while( db_step(&q)==SQLITE_ROW ){
    int idv = db_column_int(&q, 0);
    const char *zOldName = db_column_text(&q, 1);
    const char *zNewName = db_column_text(&q, 2);
    fossil_print("RENAME %s -> %s\n", zOldName, zNewName);
    undo_save(zOldName);
    undo_save(zNewName);
    db_multi_exec(
      "UPDATE vfile SET pathname=%Q, origname=coalesce(origname,pathname)"
      " WHERE id=%d AND vid=%d", zNewName, idv, vid
    );
    if( !dryRunFlag ){
      char *zFullOldPath = mprintf("%s%s", g.zLocalRoot, zOldName);
      char *zFullNewPath = mprintf("%s%s", g.zLocalRoot, zNewName);
      if( file_wd_islink(zFullOldPath) ){
        symlink_copy(zFullOldPath, zFullNewPath);
      }else{
        file_copy(zFullOldPath, zFullNewPath);
      }
      file_delete(zFullOldPath);
      free(zFullNewPath);
      free(zFullOldPath);
    }
  }
  db_finalize(&q);


  /* Report on conflicts
  */
  if( nConflict ){
    fossil_warning("WARNING: %d merge conflicts", nConflict);
  }
  if( nOverwrite ){
    fossil_warning("WARNING: %d unmanaged files were overwritten",
                   nOverwrite);
  }
  if( dryRunFlag ){
    fossil_warning("REMINDER: this was a dry run -"
                   " no files were actually changed.");
  }

  /*
  ** Clean up the mid and pid VFILE entries.  Then commit the changes.
  */
  db_multi_exec("DELETE FROM vfile WHERE vid!=%d", vid);
  if( pickFlag ){
    db_multi_exec("INSERT OR IGNORE INTO vmerge(id,merge) VALUES(-1,%d)",mid);
    /* For a cherry-pick merge, make the default check-in comment the same
    ** as the check-in comment on the check-in that is being merged in. */
    db_multi_exec(
       "REPLACE INTO vvar(name,value)"
       " SELECT 'ci-comment', coalesce(ecomment,comment) FROM event"
       "  WHERE type='ci' AND objid=%d",
       mid
    );
  }else if( backoutFlag ){
    db_multi_exec("INSERT OR IGNORE INTO vmerge(id,merge) VALUES(-2,%d)",pid);
  }else if( integrateFlag ){
    db_multi_exec("INSERT OR IGNORE INTO vmerge(id,merge) VALUES(-4,%d)",mid);
  }else{
    db_multi_exec("INSERT OR IGNORE INTO vmerge(id,merge) VALUES(0,%d)", mid);
  }
  undo_finish();
  db_end_transaction(dryRunFlag);
}