Esempio n. 1
0
bf::path CopySymlink::target() const {
  int readBytes;
  struct stat st;
  while(true) {
    CHECK_RETVAL(::lstat(base_path().c_str(), &st));
    char buffer[st.st_size+1];
    readBytes = ::readlink(base_path().c_str(), buffer, st.st_size+1);
    buffer[st.st_size] = '\0';
    if (readBytes == st.st_size) { //If readBytes > st.st_size, then the size of the symlink changed between the ::lstat and the ::readlink call
      return buffer;
    }
  }
}
Esempio n. 2
0
void CopyDir::createDir(const string &name, mode_t mode, uid_t uid, gid_t gid) {
  //TODO uid/gid?
  auto dir_path = base_path() / name;
  //Create dir
  int retval = ::mkdir(dir_path.c_str(), mode);
  CHECK_RETVAL(retval);
}
Esempio n. 3
0
  void MultiresImagePlugin::SaveConfig(YAML::Emitter& emitter, const std::string& path)
  {
    boost::filesystem::path abs_path(ui_.path->text().toStdString());
    boost::filesystem::path base_path(path);
    boost::filesystem::path rel_path = MakePathRelative(abs_path, base_path);

    emitter << YAML::Key << "path" << YAML::Value << rel_path.string();
  }
Esempio n. 4
0
String Get(Key key, const String& relative_path) {
    boost::filesystem::path rel_path(relative_path);
    // If they actually gave us a relative path, just hand it back
    if (rel_path.is_complete()) return relative_path;

    boost::filesystem::path base_path(Get(key));
    return (base_path / rel_path).string();
}
Esempio n. 5
0
void write_server_file(struct info_file *info_file) {

    if (file_exists("%sinfo/current", CVS_DIR)) {

        struct info_file* cur = read_server_file(-1);
        info_file->version = cur->version + 1;
    }

    char path[MAX_PATH_LENGTH];

    sprintf(path, "%sinfo/%d", CVS_DIR, info_file->version);

    __write_server_file(info_file, path);

    run_bash("rm %s/info/current 2> /dev/null", base_path());
    run_bash("ln %s/info/%d %s/info/current", base_path(), info_file->version, base_path());
}
Esempio n. 6
0
unique_ref<vector<CopyDir::Entry>> CopyDir::children() const {
  DIR *dir = ::opendir(base_path().c_str());
  if (dir == nullptr) {
    throw fspp::fuse::FuseErrnoException(errno);
  }

  // Set errno=0 so we can detect whether it changed later
  errno = 0;

  auto result = make_unique_ref<vector<Entry>>();

  struct dirent *entry = ::readdir(dir);
  while(entry != nullptr) {
#ifdef _DIRENT_HAVE_D_TYPE
    if(entry->d_type == DT_DIR) {
      result->push_back(Entry(EntryType::DIR, entry->d_name));
    } else if(entry->d_type == DT_REG) {
      result->push_back(Entry(EntryType::FILE, entry->d_name));
    } else if (entry->d_type == DT_LNK) {
      result->push_back(Entry(EntryType::SYMLINK, entry->d_name));
    }  // else: Ignore files we can't handle (e.g. block device, pipe, ...)
#else
    if(bf::is_symlink(base_path() / entry->d_name)) { //We have to check for symlink first, because bf::is_directory/bf::is_regular_file return true if the symlink is pointing to a respective entry
     result->push_back(Entry(EntryType::SYMLINK, entry->d_name));
    } else if(bf::is_regular_file(base_path() / entry->d_name)) {
      result->push_back(Entry(EntryType::FILE, entry->d_name));
    } else if(bf::is_directory(base_path() / entry->d_name)) {
      result->push_back(Entry(EntryType::DIR, entry->d_name));
    } // else: Ignore files we can't handle (e.g. block device, pipe, ...)
#endif
    entry = ::readdir(dir);
  }
  //On error, ::readdir returns nullptr and sets errno.
  if (errno != 0) {
    int readdir_errno = errno;
    ::closedir(dir);
    throw fspp::fuse::FuseErrnoException(readdir_errno);
  }
  int retval = ::closedir(dir);
  CHECK_RETVAL(retval);
  return result;
}
Esempio n. 7
0
			void simple_file_logger::asynch_configure() {
				try {
					config_data config = do_config(false);

					format_ = config.format;
					max_size_ = config.max_size;
					file_ = settings_manager::get_proxy()->expand_path(config.file);
					if (file_.empty())
						file_ = base_path() + "nsclient.log";
					if (file_.find('\\') == std::string::npos && file_.find('/') == std::string::npos) {
						file_ = base_path() + file_;
					}
					if (file_ == "none") {
						file_ = "";
					}
				} catch (const std::exception &e) {
					// ignored, since this might be after shutdown...
				} catch (...) {
					// ignored, since this might be after shutdown...
				}
			}
Esempio n. 8
0
unique_ref<fspp::OpenFile> CopyDir::createAndOpenFile(const string &name, mode_t mode, uid_t uid, gid_t gid) {
  //TODO uid/gid?
  auto file_path = base_path() / name;
  if (bf::exists(file_path)) {
	throw fspp::fuse::FuseErrnoException(EEXIST);
  }
  //Create file
  int fd = ::creat(file_path.c_str(), mode);
  CHECK_RETVAL(fd);
  //TODO Don't close and reopen, that's inperformant
  ::close(fd);
  return make_unique_ref<CopyOpenFile>(device(), path() / name, O_RDWR | O_TRUNC);
}
int SplitDataSet(const char *base_path_char, const char *split_path_char, float split_ratio) {
	RandGen rand_gen;
	fs::path				base_path(base_path_char), split_path(split_path_char), desc_base_path[DESCRIPTORS_NUM], desc_split_path[DESCRIPTORS_NUM];
	fs::directory_iterator	eod;
	boost::smatch			what;	
	boost::regex			filter(".*dat");

	CHECK(fs::exists(base_path));
	// if doesn't exist create a split folder
	try {
		if (fs::is_directory(split_path) == false)
			fs::create_directories(split_path);
	} catch(boost::filesystem::filesystem_error e) { 
		LOGF() << "Failed to create split folder: " << split_path << std::endl;
		return -1;
	}

	for (int desc_type = 0; desc_type < DESCRIPTORS_NUM; desc_type++) {
		desc_base_path[desc_type] = base_path/fs::path(ActionClassifier::desc_names_[desc_type]);
		desc_split_path[desc_type] = split_path/fs::path(ActionClassifier::desc_names_[desc_type]);
		CHECK(fs::exists(desc_base_path[desc_type]));
		// if doesn't exist create a split folder
		try {
			if (fs::is_directory(desc_split_path[desc_type]) == false)
				fs::create_directories(desc_split_path[desc_type]);
		} catch(boost::filesystem::filesystem_error e) { 
			LOGF() << "Failed to create split folder: " << desc_split_path[desc_type] << std::endl;
			return -1;
		}
	}
	
	for(fs::directory_iterator dir_iter(desc_base_path[TRJ]) ; (dir_iter != eod); ++dir_iter) {			
		if ((fs::is_regular_file(*dir_iter)) && (boost::regex_match(dir_iter->path().string(), what, filter))) {
			// randomly split base folder, move ALL descriptors for a specific action
			if (rand_gen.RandFloat(1.0f) < split_ratio) {
				std::string filename = dir_iter->path().filename().string();

				for (int desc_type = 0; desc_type < DESCRIPTORS_NUM; desc_type++) {
					fs::path org_path = desc_base_path[desc_type]/fs::path(filename);
					fs::path new_path = desc_split_path[desc_type]/fs::path(filename);
					LOGI() << "Moving " << org_path.string() << " to " << new_path.string() << std::endl;
					fs::rename(org_path, new_path);					
				}
			}
		}
	}
	
	return 0;
}
Esempio n. 10
0
char *
pseudo_root_path(const char *func, int line, int dirfd, const char *path, int leave_last) {
	char *rc;
	pseudo_antimagic();
	rc = base_path(dirfd, path, leave_last);
	pseudo_magic();
	if (!rc) {
		pseudo_diag("couldn't allocate absolute path for '%s'.\n",
			path);
	}
	pseudo_debug(3, "root_path [%s, %d]: '%s' from '%s'\n",
		func, line,
		rc ? rc : "<nil>",
		path ? path : "<nil>");
	return rc;
}
Esempio n. 11
0
  void MultiresImagePlugin::LoadConfig(const YAML::Node& node, const std::string& path)
  {
    std::string path_string;
    node["path"] >> path_string;

    boost::filesystem::path image_path(path_string);
    if (image_path.is_complete() == false)
    {
      boost::filesystem::path base_path(path);
      path_string =
        (path / image_path.relative_path()).normalize().string();
    }

    ui_.path->setText(path_string.c_str());

    AcceptConfiguration();
  }
Esempio n. 12
0
Archive *OpenArchive(const char *path)
{
	std::string base_path(path);

	Archive *sz_archive = new SzArchive();
	if (sz_archive->Open(base_path.c_str()) || sz_archive->Open((base_path + ".7z").c_str()) || sz_archive->Open((base_path + ".7Z").c_str()))
		return sz_archive;
	delete sz_archive;

	Archive *zip_archive = new ZipArchive();
	if (zip_archive->Open(base_path.c_str()) || zip_archive->Open((base_path + ".zip").c_str()) || zip_archive->Open((base_path + ".ZIP").c_str()))
		return zip_archive;
	delete zip_archive;

	printf("OpenArchive: failed to open %s\n", path);
	return NULL;
}
Esempio n. 13
0
TEST(SharedMemoryTest, Alone) {
  SharedMemory memory;
  EXPECT_TRUE(memory.get_block() == nullptr);
  EXPECT_TRUE(memory.is_null());
  std::string meta_path = base_path() + std::string("_alone");
  COERCE_ERROR(memory.alloc(meta_path, 1ULL << 21, 0));
  EXPECT_TRUE(memory.get_block() != nullptr);
  EXPECT_EQ(1ULL << 21, memory.get_size());
  EXPECT_EQ(meta_path, memory.get_meta_path());
  EXPECT_NE(0, memory.get_shmid());
  EXPECT_NE(0, memory.get_shmkey());
  EXPECT_EQ(0, memory.get_numa_node());
  EXPECT_FALSE(memory.is_null());
  EXPECT_TRUE(memory.is_owned());
  EXPECT_EQ(::getpid(), memory.get_owner_pid());
  memory.release_block();
  EXPECT_TRUE(memory.get_block() == nullptr);
  EXPECT_TRUE(memory.is_null());
}
Esempio n. 14
0
  CodeDB* CodeDB::open(STATE, const char* path) {
    CodeDB* codedb = state->vm()->new_object<CodeDB>(G(codedb));
    codedb->path(state, String::create(state, path));

    std::string base_path(path);

    // Check the CodeDB signature matches the VM.
    std::string signature_path = base_path + "/signature";
    std::ifstream signature(signature_path.c_str());
    if(signature) {
      uint64_t sig;
      signature >> sig;

      if(sig != RBX_SIGNATURE) {
        Exception::runtime_error(state,
            "the CodeDB signature is not valid for this version");
      }

      signature.close();
    } else {
Esempio n. 15
0
TEST(SharedMemoryTest, ShareFork) {
  bool was_child = false;
  {
    SharedMemory memory;
    EXPECT_TRUE(memory.get_block() == nullptr);
    EXPECT_TRUE(memory.is_null());
    std::string meta_path = base_path() + std::string("_share_fork");
    COERCE_ERROR(memory.alloc(meta_path, 1ULL << 21, 0));
    memory.get_block()[3] = 42;
    pid_t pid = ::fork();
    if (pid == -1) {
      memory.mark_for_release();
      ASSERT_ND(false);
      EXPECT_TRUE(false);
    } else if (pid == 0) {
      // child
      SharedMemory memory_child;
      memory_child.attach(meta_path);
      EXPECT_FALSE(memory_child.is_null());
      EXPECT_EQ(1ULL << 21, memory_child.get_size());
      EXPECT_EQ(meta_path, memory_child.get_meta_path());
      EXPECT_NE(0, memory_child.get_shmid());
      EXPECT_NE(0, memory_child.get_shmkey());
      EXPECT_EQ(0, memory_child.get_numa_node());
      EXPECT_EQ(42, memory_child.get_block()[3]);
      EXPECT_FALSE(memory.is_owned());
      was_child = true;
    } else {
      // parent
      int status;
      pid_t result = ::waitpid(pid, &status, 0);
      EXPECT_EQ(pid, result);
      EXPECT_EQ(0, status);
    }

    memory.release_block();
  }
  if (was_child) {
    ::_exit(0);  // otherwise, it goes on to execute the following tests again.
  }
}
Esempio n. 16
0
SpikeBridge::SpikeBridge(std::string _tag, std::string _url_root, shared_ptr<Variable> _spike_var):
    spike_variable(_spike_var), 
    message_ctx(1),  // 1 thread
    stopping(false){ 

    
    // lookup which channels are defined in the _url_root
    fs::path base_path(_url_root);
    
    // shortcut for now:
    n_spike_channels = 2;
    
    for(int i = 0; i < n_spike_channels; i++){
        std::string ch_path = (boost::format("%d") % i).str();
    
        fs::path channel_path = base_path / fs::path(ch_path);
        
        channel_paths.push_back(channel_path);
        
        std::cerr << "Queuing up channel: " << channel_path.string() << std::endl;
    }
    
    initSockets(message_ctx);
    
    for(int i = 0; i < n_spike_channels; i++){
        
        shared_ptr<zmq::socket_t> socket = sockets[i];
        
        fs::path channel_path = channel_paths[i];
        string channel_url_path("ipc://");
        channel_url_path += channel_path.string();
        const char *url_path = channel_url_path.c_str();
        socket->connect(url_path);
    }
    
}
Esempio n. 17
0
  bool tdr_reader::run(viennamesh::algorithm_handle &)
  {
    string_handle filename = get_required_input<string_handle>("filename");

    std::string path = base_path();
    std::string full_filename;

    if (!path.empty())
    {
      info(1) << "Using base path: " << path << std::endl;
      full_filename = path + "/" + filename();
    }
    else
      full_filename = filename();


    shared_ptr<H5File> file( new H5File(full_filename.c_str(), H5F_ACC_RDWR) );

    if (file->getNumObjs()!=1)
    {
      error(1) << "File has not exactly one collection (number of collections = " << file->getNumObjs() << std::endl;
      return false;
    }

    tdr_geometry geometry;
    geometry.read_collection(file->openGroup("collection"));

    geometry.correct_vertices();

    bool extrude_contacts = true;
    if ( get_input<bool>("extrude_contacts").valid() )
      extrude_contacts = get_input<bool>("extrude_contacts")();

    double extrude_contacts_scale = 1.0;
    if ( get_input<double>("extrude_contacts_scale").valid() )
      extrude_contacts_scale = get_input<double>("extrude_contacts_scale")();

    mesh_handle output_mesh = make_data<mesh_handle>();
    geometry.to_viennagrid( output_mesh(), extrude_contacts, extrude_contacts_scale );

    if ( get_input<bool>("fill_triangle_contacts").valid() && get_input<bool>("fill_triangle_contacts")() )
      fill_triangle_contacts( output_mesh() );






    std::vector<viennagrid::quantity_field> quantity_fields = geometry.quantity_fields( output_mesh() );
    if (!quantity_fields.empty())
    {
      quantity_field_handle output_quantity_fields = make_data<viennagrid::quantity_field>();
      output_quantity_fields.resize( quantity_fields.size() );

      for (std::size_t i = 0; i != quantity_fields.size(); ++i)
        output_quantity_fields.set(i, quantity_fields[i]);

      set_output( "quantities", output_quantity_fields );
    }

    set_output("mesh", output_mesh);

    return true;
  }
Esempio n. 18
0
const Raul::Path
ClashAvoider::map_path(const Raul::Path& in)
{
    unsigned offset = 0;
    bool has_offset = false;
    const size_t pos = in.find_last_of('_');
    if (pos != string::npos && pos != (in.length()-1)) {
        const std::string trailing = in.substr(pos + 1);
        has_offset = (sscanf(trailing.c_str(), "%u", &offset) > 0);
    }

    // Path without _n suffix
    std::string base_path_str = in;
    if (has_offset) {
        base_path_str = base_path_str.substr(0, base_path_str.find_last_of('_'));
    }

    Raul::Path base_path(base_path_str);

    SymbolMap::iterator m = _symbol_map.find(in);
    if (m != _symbol_map.end()) {
        return m->second;
    } else {
        typedef std::pair<SymbolMap::iterator, bool> InsertRecord;

        // See if parent is mapped
        Raul::Path parent = in.parent();
        do {
            SymbolMap::iterator p = _symbol_map.find(parent);
            if (p != _symbol_map.end()) {
                const Raul::Path mapped = Raul::Path(
                                              p->second.base() + in.substr(parent.base().length()));
                InsertRecord i = _symbol_map.insert(make_pair(in, mapped));
                return i.first->second;
            }
            parent = parent.parent();
        } while (!parent.is_root());

        if (!exists(in) && _symbol_map.find(in) == _symbol_map.end()) {
            // No clash, use symbol unmodified
            InsertRecord i = _symbol_map.insert(make_pair(in, in));
            assert(i.second);
            return i.first->second;

        } else {
            // Append _2 _3 etc until an unused symbol is found
            while (true) {
                Offsets::iterator o = _offsets.find(base_path);
                if (o != _offsets.end()) {
                    offset = ++o->second;
                } else {
                    string parent_str = in.parent().base();
                    parent_str = parent_str.substr(0, parent_str.find_last_of("/"));
                    if (parent_str.empty())
                        parent_str = "/";
                }

                if (offset == 0)
                    offset = 2;

                std::stringstream ss;
                ss << base_path << "_" << offset;
                if (!exists(Raul::Path(ss.str()))) {
                    std::string name = base_path.symbol();
                    if (name == "")
                        name = "_";
                    Raul::Symbol sym(name);
                    string str = ss.str();
                    InsertRecord i = _symbol_map.insert(
                                         make_pair(in, Raul::Path(str)));
                    offset = _store.child_name_offset(in.parent(), sym, false);
                    _offsets.insert(make_pair(base_path, offset));
                    return i.first->second;
                } else {
                    if (o != _offsets.end())
                        offset = ++o->second;
                    else
                        ++offset;
                }
            }
        }
    }
}
Esempio n. 19
0
TEST(SharedMemoryTest, ShareSpawn) {
  const char* env_meta_path = ::getenv("test_meta_path");
  if (env_meta_path) {
    // child process!
    {
      std::string meta_path(env_meta_path);
      std::cout << "I'm a child process(" << ::getpid()
        << "). meta_path=" << meta_path << std::endl;
      SharedMemory memory;
      memory.attach(meta_path);
      EXPECT_FALSE(memory.is_null());
      EXPECT_EQ(1ULL << 21, memory.get_size());
      EXPECT_EQ(meta_path, memory.get_meta_path());
      EXPECT_NE(0, memory.get_shmid());
      EXPECT_NE(0, memory.get_shmkey());
      EXPECT_EQ(0, memory.get_numa_node());
      EXPECT_EQ(42, memory.get_block()[3]);
      EXPECT_FALSE(memory.is_owned());
      memory.get_block()[5] = 67;
    }
    ::_exit(0);  // for the same reason, this should terminate now.
    return;
  } else {
    std::cout << "I'm a master process(" << ::getpid() << ")" << std::endl;
  }

  SharedMemory memory;
  EXPECT_TRUE(memory.get_block() == nullptr);
  EXPECT_TRUE(memory.is_null());
  std::string meta_path = base_path() + std::string("_share_spawn");
  COERCE_ERROR(memory.alloc(meta_path, 1ULL << 21, 0));
  memory.get_block()[3] = 42;


  posix_spawn_file_actions_t file_actions;
  posix_spawnattr_t attr;
  ::posix_spawn_file_actions_init(&file_actions);
  ::posix_spawnattr_init(&attr);

  std::string path = assorted::get_current_executable_path();
  // execute this test
  char* const new_argv[] = {
    const_cast<char*>(path.c_str()),
    const_cast<char*>("--gtest_filter=SharedMemoryTest.ShareSpawn"),
    nullptr};

  // with meta_path in environment variable
  std::string meta("test_meta_path=");
  meta += meta_path;
  char* const new_envp[] = {
    const_cast<char*>(meta.c_str()),
    nullptr};

  pid_t child_pid;
  std::cout << "spawning: " << path << std::endl;
  int ret = ::posix_spawn(&child_pid, path.c_str(), &file_actions, &attr, new_argv, new_envp);

  EXPECT_EQ(0, ret);
  if (ret == 0) {
    EXPECT_NE(0, child_pid);
    int status = 0;
    pid_t result = ::waitpid(child_pid, &status, 0);
    std::cout << "child process(" << child_pid << ") died. result=" << result << std::endl;
    EXPECT_EQ(child_pid, result);
    EXPECT_EQ(0, status);
  }
  assorted::memory_fence_acquire();
  EXPECT_EQ(67, memory.get_block()[5]);
  memory.release_block();
}
Esempio n. 20
0
void Sz4RPNParam::test2() {
	rpn_unit_test::IPKContainerMock2 mock;

	std::wstringstream base_dir_name;
	base_dir_name << L"/tmp/sz4_rpn_param" << getpid() << L"." << time(NULL) << L".tmp";
	boost::filesystem::wpath base_path(base_dir_name.str());
	boost::filesystem::wpath param_dir(base_path / L"BASE/szbase/A/B/C");
	boost::filesystem::create_directories(param_dir);

#if BOOST_FILESYSTEM_VERSION == 3
	sz4::base_templ<rpn_unit_test::test_types> base(base_path.wstring(), &mock);
#else
	sz4::base_templ<rpn_unit_test::test_types> base(base_path.file_string(), &mock);
#endif
	auto buff = base.buffer_for_param(mock.GetParam(L"BASE:A:B:D"));

	
	TestObserver o;
#if BOOST_FILESYSTEM_VERSION == 3
	base.param_monitor().add_observer(&o, mock.GetParam(L"BASE:A:B:C"), param_dir.native(), 10);
#else
	base.param_monitor().add_observer(&o, mock.GetParam(L"BASE:A:B:C"), param_dir.external_file_string(), 10);
#endif
	{
		sz4::weighted_sum<double, sz4::second_time_t> sum;
		buff->get_weighted_sum(mock.GetParam(L"BASE:A:B:D"), 100u, 200u, PT_SEC10, sum);
		CPPUNIT_ASSERT_EQUAL(sz4::time_difference<sz4::second_time_t>::type(0), sum.weight());
		CPPUNIT_ASSERT_EQUAL(sz4::time_difference<sz4::second_time_t>::type(100), sum.no_data_weight());
		CPPUNIT_ASSERT_EQUAL(false, sum.fixed());

		std::wstringstream file_name;
		file_name << std::setfill(L'0') << std::setw(10) << 100 << L".sz4";
		std::string file_path_str;
#if BOOST_FILESYSTEM_VERSION == 3
		file_path_str = (param_dir / file_name.str()).native();
#else
		file_path_str = (param_dir / file_name.str()).external_file_string();
#endif
		int fd;
		CPPUNIT_ASSERT_NO_THROW(fd = sz4::open_writelock(file_path_str.c_str(), O_WRONLY | O_CREAT));

		char buf[3];
		short v = 10;
		unsigned char t = 0x32;

		memcpy(buf, &v, 2);
		memcpy(buf + 2, &t, 1);

		write(fd, buf, sizeof(buf));

		sz4::close_unlock(fd);
	}

	CPPUNIT_ASSERT(o.wait_for(1, 2));
	{
		sz4::weighted_sum<double, sz4::second_time_t> sum;
		sz4::weighted_sum<double, sz4::second_time_t>::time_diff_type weight;
		buff->get_weighted_sum(mock.GetParam(L"BASE:A:B:D"), 100u, 200u, PT_SEC10, sum);
		CPPUNIT_ASSERT_EQUAL(550., double(sum.sum(weight)));
		CPPUNIT_ASSERT_EQUAL(sz4::time_difference<sz4::second_time_t>::type(50), weight);
		CPPUNIT_ASSERT_EQUAL(sz4::time_difference<sz4::second_time_t>::type(50), sum.no_data_weight());
		CPPUNIT_ASSERT_EQUAL(false, sum.fixed());
	}
}
Esempio n. 21
0
CopyDir::CopyDir(CopyDevice *device, const bf::path &path)
  :CopyNode(device, path) {
  ASSERT(bf::is_directory(base_path()), "Path isn't a valid directory");
}
Esempio n. 22
0
			simple_file_logger::simple_file_logger(std::string file) : max_size_(0), format_("%Y-%m-%d %H:%M:%S") {
				file_ = base_path() + file;
			}
Esempio n. 23
0
void CopyDir::remove() {
  int retval = ::rmdir(base_path().c_str());
  CHECK_RETVAL(retval);
}
Esempio n. 24
0
void CopySymlink::remove() {
  int retval = ::unlink(base_path().c_str());
  CHECK_RETVAL(retval);
}
Esempio n. 25
0
void CCTestFrame::Start()
{
    if (m_ParserCtrl) m_ParserCtrl->SetSelection(1); // make sure "Output" tab is selected

    CCTestAppGlobal::s_includeDirs.Clear();
    CCTestAppGlobal::s_fileQueue.Clear();
    CCTestAppGlobal::s_filesParsed.Clear();

    // Obtain all include directories
    wxStringTokenizer tkz_inc(m_IncludeCtrl->GetValue(), _T("\r\n"));
    while ( tkz_inc.HasMoreTokens() )
    {
        wxString include = tkz_inc.GetNextToken().Trim(true).Trim(false);
        if (!include.IsEmpty())
            CCTestAppGlobal::s_includeDirs.Add(include);
    }

    if (m_DoHeadersCtrl->IsChecked())
    {
        // Obtain all priority header files
        wxStringTokenizer tkz_hdr(m_HeadersCtrl->GetValue(), _T(","));
        while (tkz_hdr.HasMoreTokens())
        {
            wxString header = tkz_hdr.GetNextToken().Trim(false).Trim(true);

            // Remove <> (if any)
            int lt = header.Find(wxT('<')); int gt = header.Find(wxT('>'),true);
            if (lt!=wxNOT_FOUND && gt!=wxNOT_FOUND && gt>lt)
                header = header.AfterFirst(wxT('<')).BeforeLast(wxT('>'));
            // Remove "" (if any)
            int oq = header.Find(wxT('"')); int cq = header.Find(wxT('"'),true);
            if (oq!=wxNOT_FOUND && cq!=wxNOT_FOUND && cq>oq)
                header = header.AfterFirst(wxT('"')).BeforeLast(wxT('"'));

            header = header.Trim(false).Trim(true);

            // Find the header files in include path's as provided
            // (practically the same as ParserBase::FindFileInIncludeDirs())
            for (size_t i=0; i<CCTestAppGlobal::s_includeDirs.GetCount(); ++i)
            {
                // Normalize the path (as in C::B's "NormalizePath()")
                wxFileName f_header(header);
                wxString   base_path(CCTestAppGlobal::s_includeDirs[i]);
                if (f_header.Normalize(wxPATH_NORM_ALL & ~wxPATH_NORM_CASE, base_path))
                {
                    wxString this_header = f_header.GetFullPath();
                    if ( ::wxFileExists(this_header) )
                        CCTestAppGlobal::s_fileQueue.Add(this_header);
                }
            }
        }
    }

    if (CCTestAppGlobal::s_fileQueue.IsEmpty() && !m_Control->GetLength())
    {
        wxMessageBox(wxT("Main file not found and buffer empty. Nothing to do."),
                     _("Information"), wxOK | wxICON_INFORMATION, this);
        return;
    }

    if (m_DoHideCtrl && m_DoHideCtrl->IsChecked()) Hide();

    m_ProgDlg = new wxProgressDialog(_T("Please wait, operating..."), _("Preparing...\nPlease wait..."), 0, this, wxPD_APP_MODAL);
    m_ProgDlg->SetSize(640,100);
    m_ProgDlg->Layout();
    m_ProgDlg->CenterOnParent();

    m_LogCount = 0;
    m_LogCtrl->Clear();
    CCTest::Get()->Clear(); // initial clearance

    // make sure not to over-write an existing file (in case content had changed)
    wxString tf(wxFileName::CreateTempFileName(wxT("cc")));
    // make the parser recognise it as header file:
    wxFileName fn(tf); fn.SetExt(wxT("h")); wxRemoveFile(tf); // no longer needed
    if (m_Control->SaveFile(fn.GetFullPath()))
        CCTestAppGlobal::s_fileQueue.Add(fn.GetFullPath());
    else
        AppendToLog(_T("Unable to parse buffer (could not convert to file)."));

    AppendToLog(_T("--------------M-a-i-n--L-o-g--------------\r\n\r\n"));

    // parse file from the queue one-by-one
    while (!CCTestAppGlobal::s_fileQueue.IsEmpty())
    {
        wxString file = CCTestAppGlobal::s_fileQueue.Item(0);
        CCTestAppGlobal::s_fileQueue.Remove(file);
        if (file.IsEmpty()) continue;

        AppendToLog(_T("-----------I-n-t-e-r-i-m--L-o-g-----------"));
        m_CurrentFile = file;

        m_ProgDlg->Update(-1, m_CurrentFile);
        m_StatuBar->SetStatusText(m_CurrentFile);

        // This is the core parse stage for files
        CCTest::Get()->Start(m_CurrentFile);
        CCTestAppGlobal::s_filesParsed.Add(m_CurrentFile); // done
    }
    // don't forget to remove the temporary file (w/ ".h" extension)
    wxRemoveFile(fn.GetFullPath());

    m_ProgDlg->Update(-1, wxT("Creating tree log..."));
    AppendToLog(_T("--------------T-r-e-e--L-o-g--------------\r\n"));
    CCTest::Get()->PrintTree();

    m_ProgDlg->Update(-1, wxT("Creating list log..."));
    AppendToLog(_T("--------------L-i-s-t--L-o-g--------------\r\n"));
    CCTest::Get()->PrintList();

    if (m_DoTreeCtrl->IsChecked())
    {
        m_ProgDlg->Update(-1, wxT("Serializing tree..."));

        Freeze();
        m_TreeCtrl->SetValue( CCTest::Get()->SerializeTree() );
        Thaw();
    }

    // Here we are going to test the expression solving algorithm

    NativeParserTest nativeParserTest;

    wxString exp = _T("obj.m_Member1");

    TokenIdxSet searchScope;
    searchScope.insert(-1);

    TokenIdxSet result;

    TokenTree *tree = CCTest::Get()->GetTokenTree();

    nativeParserTest.TestExpression(exp,
                                    tree,
                                    searchScope,
                                    result );

    wxLogMessage(_T("Result have %lu matches"), static_cast<unsigned long>(result.size()));


    for (TokenIdxSet::iterator it=result.begin(); it!=result.end(); ++it)
    {
        Token* token = tree->at(*it);
        if (token)
        {
            wxString log;
            log << token->GetTokenKindString() << _T(" ")
                << token->DisplayName()        << _T("\t[")
                << token->m_Line               << _T(",")
                << token->m_ImplLine           << _T("]");
            CCLogger::Get()->Log(log);
        }
    }


    if (m_ProgDlg) { delete m_ProgDlg; m_ProgDlg = 0; }

    if ( !IsShown() ) Show();

    TokenTree* tt = CCTest::Get()->GetTokenTree();
    if (tt)
    {
        AppendToLog((wxString::Format(_("The parser contains %lu tokens, found in %lu files."),
                                      static_cast<unsigned long>(tt->size()), static_cast<unsigned long>(tt->m_FileMap.size()))));
    }
}
Esempio n. 26
0
void CopyDir::createSymlink(const std::string &name, const boost::filesystem::path &target, uid_t uid, gid_t gid) {
  //TODO uid/gid?
  auto from_path = base_path() / name;
  int retval = ::symlink(target.c_str(), from_path.c_str());
  CHECK_RETVAL(retval);
}
Esempio n. 27
0
CopySymlink::CopySymlink(CopyDevice *device, const bf::path &path)
  :CopyNode(device, path) {
  ASSERT(bf::is_symlink(base_path()), "Path isn't valid symlink");
}