コード例 #1
0
ファイル: config.cpp プロジェクト: Hamcha/lumaupdate
LoadConfigError Config::LoadFile(const std::string& path) {
	std::ifstream cfgfile(path);

	if (!cfgfile.is_open()) {
		return LoadConfigError::NotExists;
	}

	if (!cfgfile.good()) {
		return LoadConfigError::Unreadable;
	}

	std::string curLine;
	while (std::getline(cfgfile, curLine)) {
		size_t index = curLine.find('=');
		if (index != std::string::npos) {
			std::string key = curLine.substr(0, index);
			std::string value = curLine.substr(index + 1);
			trim(key);
			trim(value);
			values[key] = value;
		} else {
			logPrintf("Invalid line detected in config: %s\n", curLine.c_str());
			return LoadConfigError::Malformed;
		}
	}

	return LoadConfigError::None;
}
コード例 #2
0
ファイル: scripts.c プロジェクト: bert/pcb-rnd
void hid_gpmi_load_dir(const char *dir, int add_pkg_path)
{
	FILE *f;
	char *cfn;

	conf_dir = dir;
	cfn = Concat(dir, PCB_DIR_SEPARATOR_S, CONFNAME,  NULL);
#ifdef CONFIG_DEBUG
	fprintf(stderr, "pcb-gpmi: opening config: %s\n", cfn);
#endif
	f = fopen(cfn, "r");
	if (f == NULL) {
		free(cfn);
#ifdef CONFIG_DEBUG
		fprintf(stderr, " ...failed\n");
#endif
		return;
	}

	if (add_pkg_path)
		gpmi_path_insert(GPMI_PATH_PACKAGES, dir);

	cfgfile(f, NULL, cfn);

	fclose(f);
	free(cfn);
	conf_dir = NULL;
}
コード例 #3
0
    // generic reset
    void testResetLogConf()
    {
        SelfDeletingFilePath cfgfile(SCXFileSystem::DecodePath("./testfiles/log.conf"));

        // Create a simple example file
        std::vector<std::wstring> lines;
        lines.push_back(L"FILE (");
        lines.push_back(L"PATH: /var/log-1");
        lines.push_back(L"MODULE: TRACE");
        lines.push_back(L"MODULE: scxtest.core.common.pal WARNING");
        lines.push_back(L"MODULE: scxtest.core.common.pal.system.common HYSTERICAL");
        lines.push_back(L"MODULE: scxtest.core.common.pal.system.common.entityenumeration INFO");
        lines.push_back(L")");
        lines.push_back(L"");   // Must be here, or else the last newline will be omitted.
        SCXFile::WriteAllLinesAsUTF8(cfgfile, lines, std::ios_base::out);

        {
            SCX_LogConfigurator subject(cfgfile);
            CPPUNIT_ASSERT (subject.Reset() );
        }

        std::string str = GetFileContent(cfgfile);

        CPPUNIT_ASSERT( str.find("HYSTERICAL")  == str.npos );              // Should be gone
        CPPUNIT_ASSERT( str.find("scxtest.core.common.pal")  == str.npos ); // should be gone
        CPPUNIT_ASSERT( str.find("FILE")  != str.npos );                    // should still be there
        CPPUNIT_ASSERT( str.find("/var/log-1")  != str.npos );              // should still be there
    }
コード例 #4
0
    // reading the exisitng one 
    void testExistingConfFile()
    {
        SelfDeletingFilePath cfgfile(SCXFileSystem::DecodePath("./testfiles/log.conf"));

        // Create a simple example file
        std::vector<std::wstring> lines;
        lines.push_back(L"FILE (");
        lines.push_back(L"PATH: /var/log-1");
        lines.push_back(L")");
        lines.push_back(L"");   // Must be here, or else the last newline will be omitted.
        SCXFile::WriteAllLinesAsUTF8(cfgfile, lines, std::ios_base::out);
        
        SCX_LogConfigurator subject(cfgfile);

        std::wostringstream  buf;
        subject.Print( buf );
        
        std::wstring str = buf.str();

        // should be some "FILE" default configuration
        CPPUNIT_ASSERT( str.size() > 0 );                        
        CPPUNIT_ASSERT( str.find(L"FILE")  != str.npos );
        CPPUNIT_ASSERT( str.find(L"/var/log-1")  != str.npos );
        CPPUNIT_ASSERT( str.find(L"INFO")  != str.npos );        // The only severity will be default INFO
    }
コード例 #5
0
    // provider set
    void testProvRemoveLogfile()
    {
        // create a file
        SelfDeletingFilePath cfgfile(SCXFileSystem::DecodePath("./testfiles/log.conf"));

        {
            SCX_LogConfigurator subject(cfgfile);

            subject.Set( L"STDOUT", L"trace" );
            subject.Set( L"STDOUT:scxtest.core.common.pal.system.common.entityenumeration", L"info" );
            subject.Set( L"FILE:/myvar/opt/microsoft/scx/log/scx.log:scxtest.core.common.pal.system.common.entityenumeration", L"info" );
        }
        
        SCX_LogConfigurator subject(cfgfile);

        subject.Remove( L"STDOUT" );

        CPPUNIT_ASSERT_THROW_MESSAGE( "exception is expected since entry does not exist",
            subject.Remove( L"FILE:/var/opt/microsoft/scx/log/scx.log" ),
            SCXAdminException );

        std::string str = GetFileContent(cfgfile);

        // we should not see these entries
        CPPUNIT_ASSERT( str.find("HYSTERICAL")  == str.npos );
        CPPUNIT_ASSERT( str.find("/var")  == str.npos );
        CPPUNIT_ASSERT( str.find("STDOUT")  == str.npos );

        // but should see these:
        CPPUNIT_ASSERT( str.find("FILE")  != str.npos );
        CPPUNIT_ASSERT( str.find("PATH: /myvar/opt/microsoft/scx/log/scx.log")  != str.npos );
        CPPUNIT_ASSERT( str.find("MODULE: scxtest.core.common.pal.system.common.entityenumeration INFO")  != str.npos );
    }
コード例 #6
0
int EDA_BASE_FRAME::ReadHotkeyConfigFile( const wxString&           aFilename,
                                          struct EDA_HOTKEY_CONFIG* aDescList )
{
    wxFileName fn( aFilename );
    fn.SetExt( DEFAULT_HOTKEY_FILENAME_EXT );

    wxFile cfgfile( fn.GetFullPath() );

    if( !cfgfile.IsOpened() )       // There is a problem to open file
        return 0;

    // get length
    cfgfile.SeekEnd();
    wxFileOffset size = cfgfile.Tell();
    cfgfile.Seek( 0 );

    // read data
    char*    buffer = new char[size];
    cfgfile.Read( buffer, size );

    wxString data( buffer, wxConvUTF8 );

    // parse
    ParseHotkeyConfig( data, aDescList );

    // cleanup
    delete[] buffer;
    cfgfile.Close();
    return 1;
}
コード例 #7
0
  /** Check the command-line arguments for a --config-file (or -c) switch.
   * If it is there, see if the file specified after is a valid file.  If
   * so, that's our config file. */
  static bool checkArgs(int argc, char** argv, string& result)
  {
    // Describe command-line args we are looking for.
    bpo::options_description desc;
    desc.add_options()
      ("config-file,c", bpo::value<string>() );

    // Load args into memory.
    bpo::variables_map vm;
    bpo::store(bpo::parse_command_line(argc, argv, desc), vm);
    bpo::notify(vm);

    // If the arg we want is specified...
    if ( vm.count("config-file") )
    {
      bfs::path cfgfile( vm["config-file"].as<string>() );
      // ... and if it is a valid file...
      if ( bfs::exists(cfgfile) )
      {
        // ... then it's our config file.
        result = cfgfile.string();
        return true;
      }
    }
    return false;
  }
コード例 #8
0
ファイル: team.cpp プロジェクト: sopel/hw
bool HWTeam::deleteFile()
{
    if(m_isNetTeam)
        return false;
    QFile cfgfile(QString("physfs://Teams/%1.hwt").arg(DataManager::safeFileName(m_name)));
    cfgfile.remove();
    return true;
}
コード例 #9
0
ファイル: dtkLogger.cpp プロジェクト: papadop/dtk
/*!
    \internal
    Slot for filewatcher
*/
void dtkLoggingPrivate::fileChanged(const QString &path)
{
    if (path == _configFile) {
        QFile cfgfile(_configFile);
        readSettings(cfgfile);
        _configFileWatcher->addPath(path);
    }
}
コード例 #10
0
bool HWTeam::DeleteFile()
{
    if(m_isNetTeam)
        return false;
    QFile cfgfile(cfgdir->absolutePath() + "/Teams/" + TeamName + ".hwt");
    cfgfile.remove();
    return true;
}
コード例 #11
0
    // set "verbose" - should create a file
    void testCreatingConfFile()
    {
        // This file should not exist.
        SelfDeletingFilePath cfgfile(SCXFileSystem::DecodePath("./testfiles/log.conf"));

        SCX_LogConfigurator subject(cfgfile);

        CPPUNIT_ASSERT( subject.Set( SCX_AdminLogAPI::eLogLevel_Verbose ) );
        CPPUNIT_ASSERT( SCXFile::Exists(cfgfile) ); // Should be created
    }
コード例 #12
0
ファイル: Env.cpp プロジェクト: batela/Container-src
void Env::ReadFile()
{
    string id, eq, val,line;
    ifstream cfgfile (configFile.c_str());

    while(getline((std::istream&)cfgfile, line))
    {
    	//cout << "Leido.." << line << "\n";
      if ((line[0] == '#') || (line.find("=")==std::string::npos)) continue;  // skip comments
      vector<string> items = this->split (line,'=');
      configValues.insert(std::pair<string,string> (items[0],items[1]));
    }
}
コード例 #13
0
ファイル: dtkLogger.cpp プロジェクト: papadop/dtk
/*!
    \internal
    Function to set the logging config file.
    This function set the new dtkLogging configuration config file.
    If QT_LOGGING_CONFIG is set this function will do nothing.
*/
void dtkLoggingPrivate::setLoggingRulesFile(const QString &path)
{
    _registerCategories = false;
    _configFile = path;

    if (!_configFileWatcher) {
        QMetaObject::invokeMethod(this, "createFileWatcher");
    }

    QFile cfgfile(_configFile);

    readSettings(cfgfile);
}
コード例 #14
0
    /**
        The log file backend path in provider log configuration should be 
        case sensitive.
     */   
    void testProviderLogFilePathIsCaseSensitive()
    {
        SelfDeletingFilePath cfgfile(SCXFileSystem::DecodePath("log.conf"));
        cfgfile.SetDirectory(L"./testfiles/");

        SCX_LogConfigurator subject(cfgfile);

        subject.Set( L"FILE:/var/opt/microsoft/scx/log/scx.log:module", L"TRACE" );
        subject.Set( L"FILE:/VAR/Opt/Microsoft/scx/log/scx.log:module", L"ERROR" );

        CPPUNIT_ASSERT( L"TRACE" == GetLogLevel(cfgfile, L"FILE", L"/var/opt/microsoft/scx/log/scx.log", L"module") );
        CPPUNIT_ASSERT( L"ERROR" == GetLogLevel(cfgfile, L"FILE", L"/VAR/Opt/Microsoft/scx/log/scx.log", L"module") );
    }
コード例 #15
0
 /** Check the environment for a config file. */
 static bool checkEnv(string& result)
 {
   // See if our environment variable exists.
   char* env_var = getenv(CFG_ENV_VAR.c_str());
   if (env_var) {
     bfs::path cfgfile(env_var);
     // If it does, make sure the file path is valid.
     if ( bfs::exists(cfgfile) ) {
       result = cfgfile.string();
       return true;
     }
   }
   return false;
 }
コード例 #16
0
ファイル: parser.cpp プロジェクト: NightsWatch/compilers-lab
void Parser::getGrammar(string fname)
{
	ifstream cfgfile(fname.c_str());
	string line;
	if (cfgfile.is_open())
  	{
  		int linenum=0;
		while(getline(cfgfile, line))
		{
			istringstream iss(line);

			vector<string> tokens;
			copy(istream_iterator<string>(iss),
         		istream_iterator<string>(),
         		back_inserter<vector<string> >(tokens));

			set<string> productions;
			if(linenum==0)
			{
  				/* finding the list of terminals */
  				// if(strcmp(tokens[0],"t:")!=0) break;
				for(int i=1;i<tokens.size();i++)
				{
				  terminals.insert(tokens[i]);
				}
				linenum++;
				continue;

			}

			// Adding the list of nonterminals
			nonterminals.insert(tokens[0]);

		/* adding productions to the grammar -*/
			for(int i=1;i<tokens.size();i++)
				{
				  productions.insert(tokens[i]);
				}
			grammar.insert( std::pair<string, set<string> >(tokens[0],productions) );

  
		}

		cfgfile.close();
	}
	cout<<"Grammar is:"<<endl;
	printMap(grammar);
	cout<<endl;
}
コード例 #17
0
    // 
    // check if default one
    void testNoConfFile()
    {
        // This file should not exist.
        SelfDeletingFilePath cfgfile(SCXFileSystem::DecodePath("./testfiles/log.conf"));

        SCX_LogConfigurator subject(cfgfile);

        std::wostringstream  buf;
        subject.Print( buf );
        std::wstring str = buf.str();

        // should be some "FILE" default configuration
        CPPUNIT_ASSERT( str.size() > 0 );
        CPPUNIT_ASSERT( str.find(L"FILE")  != str.npos );
    }
コード例 #18
0
    /**
        The severity threshold in provider log configuration should be 
        case insensitive.
     */   
    void testProviderLogSeverityIsCaseInsensitive()
    {
        SelfDeletingFilePath cfgfile(SCXFileSystem::DecodePath("log.conf"));
        cfgfile.SetDirectory(L"./testfiles/");

        SCX_LogConfigurator subject(cfgfile);

        subject.Set( L"STDOUT:module", L"trace" );
        subject.Set( L"STDOUT:MODULE", L"TrAcE" );
        subject.Set( L"STDOUT:MoDuLe", L"TRACE" );

        CPPUNIT_ASSERT( L"TRACE" == GetLogLevel(cfgfile, L"STDOUT", L"", L"module") );
        CPPUNIT_ASSERT( L"TRACE" == GetLogLevel(cfgfile, L"STDOUT", L"", L"MODULE") );
        CPPUNIT_ASSERT( L"TRACE" == GetLogLevel(cfgfile, L"STDOUT", L"", L"MoDuLe") );
    }
コード例 #19
0
    // Negative test to set invalid entry: should throw an exception
    void testSetInvalidSeverityThrows()
    {
        SelfDeletingFilePath cfgfile(SCXFileSystem::DecodePath("./testfiles/log.conf"));
        SCX_LogConfigurator invTest(cfgfile);

        invTest.Set( L"STDOUT", L"trace" );

        CPPUNIT_ASSERT_THROW_MESSAGE( "invalid severity string: anything1",
            invTest.Set( L"STDOUT:scxtest.core.common.pal.system.common.entityenumeration", L"anything" ),
            SCXAdminException );

        CPPUNIT_ASSERT_THROW_MESSAGE( "invalid severity string: anything2",
            invTest.Set( L"FILE:/myvar/opt/microsoft/scx/log/scx.log:scxtest.core.common.pal.system.common.entityenumeration", L"anything2" ),
            SCXAdminException );
    }
コード例 #20
0
    /**
        The log backend name (FILE or STDOUT) in provider log configuration should be 
        case insensitive.
     */   
    void testProviderLogBackendNameIsCaseInsensitive()
    {
        SelfDeletingFilePath cfgfile(SCXFileSystem::DecodePath("log.conf"));
        cfgfile.SetDirectory(L"./testfiles/");

        SCX_LogConfigurator subject(cfgfile);

        subject.Set( L"STDOUT:module", L"TRACE" );
        subject.Set( L"stdout:module", L"INFO" );

        subject.Set( L"FILE:/var/opt/microsoft/scx/log/scx.log:module", L"TRACE" );
        subject.Set( L"file:/var/opt/microsoft/scx/log/scx.log:module", L"ERROR" );

        CPPUNIT_ASSERT( L"INFO" == GetLogLevel(cfgfile, L"STDOUT", L"", L"module") );
        CPPUNIT_ASSERT( L"ERROR" == GetLogLevel(cfgfile, L"FILE", L"/var/opt/microsoft/scx/log/scx.log", L"module") );
    }
コード例 #21
0
ファイル: scripts.c プロジェクト: bert/pcb-rnd
int gpmi_hid_script_remove(hid_gpmi_script_info_t *i)
{
	FILE *fin, *fout;
	int n;
	char *tmpfn;
	int res;

	if (i->conffile_name == NULL) {
		Message("gpmi_hid_script_remove(): can't remove script from configs, the script is not loaded from a config.\n");
		return -1;
	}

	fin = fopen(i->conffile_name, "r");
	if (fin == NULL) {
		Message("gpmi_hid_script_remove(): can't remove script from configs, can't open %s for read.\n", i->conffile_name);
		return -1;
	}
	tmpfn = Concat(i->conffile_name, ".tmp", NULL);
	fout = fopen(tmpfn, "w");
	if (fout == NULL) {
		Message("gpmi_hid_script_remove(): can't remove script from configs, can't create %s.\n", tmpfn);
		fclose(fin);
		free(tmpfn);
		return -1;
	}

	res = cfgfile(fin, fout, i->name);

	fclose(fin);
	fclose(fout);

	if (res < 1) {
		Message("gpmi_hid_script_remove(): can't remove script from configs, can't find the correspondign config line in %s\n", i->conffile_name);
		free(tmpfn);
		return -1;
	}

	if (rename(tmpfn, i->conffile_name) != 0) {
		Message("gpmi_hid_script_remove(): can't remove script from configs, can't move %s to %s.\n", tmpfn, i->conffile_name);
		free(tmpfn);
		return -1;
	}

	free(tmpfn);
	return 0;
}
コード例 #22
0
ファイル: team.cpp プロジェクト: sopel/hw
bool HWTeam::saveToFile()
{
    if (OldTeamName != m_name)
    {
        QFile cfgfile(QString("physfs://Teams/%1.hwt").arg(DataManager::safeFileName(OldTeamName)));
        cfgfile.remove();
        OldTeamName = m_name;
    }

    QString fileName = QString("physfs://Teams/%1.hwt").arg(DataManager::safeFileName(m_name));
    DataManager::ensureFileExists(fileName);
    QSettings teamfile(fileName, QSettings::IniFormat, 0);
    teamfile.setIniCodec("UTF-8");
    teamfile.setValue("Team/Name", m_name);
    teamfile.setValue("Team/Grave", m_grave);
    teamfile.setValue("Team/Fort", m_fort);
    teamfile.setValue("Team/Voicepack", m_voicepack);
    teamfile.setValue("Team/Flag", m_flag);
    teamfile.setValue("Team/Difficulty", m_difficulty);
    teamfile.setValue("Team/Rounds", m_rounds);
    teamfile.setValue("Team/Wins", m_wins);
    teamfile.setValue("Team/CampaignProgress", m_campaignProgress);

    for(int i = 0; i < HEDGEHOGS_PER_TEAM; i++)
    {
        QString hh = QString("Hedgehog%1/").arg(i);
        teamfile.setValue(hh + "Name", m_hedgehogs[i].Name);
        teamfile.setValue(hh + "Hat", m_hedgehogs[i].Hat);
        teamfile.setValue(hh + "Rounds", m_hedgehogs[i].Rounds);
        teamfile.setValue(hh + "Kills", m_hedgehogs[i].Kills);
        teamfile.setValue(hh + "Deaths", m_hedgehogs[i].Deaths);
        teamfile.setValue(hh + "Suicides", m_hedgehogs[i].Suicides);
    }
    for(int i = 0; i < BINDS_NUMBER; i++)
        teamfile.setValue(QString("Binds/%1").arg(m_binds[i].action), m_binds[i].strbind);
    for(int i = 0; i < MAX_ACHIEVEMENTS; i++)
        if(achievements[i][0][0])
            teamfile.setValue(QString("Achievements/%1").arg(achievements[i][0]), AchievementProgress[i]);
        else
            break;

    return true;
}
コード例 #23
0
    // provider set
    void testProvSetThresholdForStdOut()
    {
        SelfDeletingFilePath cfgfile(SCXFileSystem::DecodePath("./testfiles/log.conf"));

        SCX_LogConfigurator subject(cfgfile);

        // set several entries: should create a new file with specific entries:
        subject.Set( L"STDOUT", L"TRACE" );
        subject.Set( L"STDOUT:scxtest.core.common.pal.system.common.entityenumeration", L"INFO" );

        std::string str = GetFileContent(cfgfile);

        // we should not see these entries
        CPPUNIT_ASSERT( str.find("HYSTERICAL")  == str.npos );
        CPPUNIT_ASSERT( str.find("FILE")  == str.npos );
        CPPUNIT_ASSERT( str.find("/var")  == str.npos );

        // but should see these:
        CPPUNIT_ASSERT( L"TRACE" == GetLogLevel(cfgfile, L"STDOUT", L"", L"") );
        CPPUNIT_ASSERT( L"INFO" == GetLogLevel(cfgfile, L"STDOUT", L"", L"scxtest.core.common.pal.system.common.entityenumeration") );
    }
コード例 #24
0
bool HWTeam::SaveToFile()
{
    if (OldTeamName != TeamName)
    {
        QFile cfgfile(cfgdir->absolutePath() + "/Teams/" + OldTeamName + ".hwt");
        cfgfile.remove();
        OldTeamName = TeamName;
    }
    QSettings teamfile(cfgdir->absolutePath() + "/Teams/" + TeamName + ".hwt", QSettings::IniFormat, 0);
    teamfile.setIniCodec("UTF-8");
    teamfile.setValue("Team/Name", TeamName);
    teamfile.setValue("Team/Grave", Grave);
    teamfile.setValue("Team/Fort", Fort);
    teamfile.setValue("Team/Voicepack", Voicepack);
    teamfile.setValue("Team/Flag", Flag);
    teamfile.setValue("Team/Difficulty", difficulty);
    teamfile.setValue("Team/Rounds", Rounds);
    teamfile.setValue("Team/Wins", Wins);
    teamfile.setValue("Team/CampaignProgress", CampaignProgress);
    for(int i = 0; i < 8; i++)
    {
        QString hh = QString("Hedgehog%1/").arg(i);
        teamfile.setValue(hh + "Name", Hedgehogs[i].Name);
        teamfile.setValue(hh + "Hat", Hedgehogs[i].Hat);
        teamfile.setValue(hh + "Rounds", Hedgehogs[i].Rounds);
        teamfile.setValue(hh + "Kills", Hedgehogs[i].Kills);
        teamfile.setValue(hh + "Deaths", Hedgehogs[i].Deaths);
        teamfile.setValue(hh + "Suicides", Hedgehogs[i].Suicides);
    }
    for(int i = 0; i < BINDS_NUMBER; i++)
        teamfile.setValue(QString("Binds/%1").arg(binds[i].action), binds[i].strbind);
    for(int i = 0; i < MAX_ACHIEVEMENTS; i++)
        if(achievements[i][0][0])
            teamfile.setValue(QString("Achievements/%1").arg(achievements[i][0]), AchievementProgress[i]);
        else
            break;
    return true;
}
コード例 #25
0
int main(int argc, const char* argv[])
{
	Game g;

	ifstream cfgfile("monopoly.cfg");

	g.load(cfgfile);

	cfgfile.close();

	cout << "Game is loaded and ready to start!!!" << endl;

	cin.ignore();

	GameRunner runner(g, 20);					// run for 10 rolls!

	runner.runGame();
	
	cout << "Game is finished!!!" << endl;

	cin.ignore();

	return 0;
}
コード例 #26
0
/**
 * Function ReadHotkeyConfigFile
 * Read an old configuration file (&ltfile&gt.key) and fill the current hotkey list
 * with hotkeys
 * @param aFilename = file name to read.
 * @param aDescList = current hotkey list descr. to initialise.
 */
int EDA_BASE_FRAME::ReadHotkeyConfigFile( const wxString&           aFilename,
                                          struct EDA_HOTKEY_CONFIG* aDescList )
{
    wxFile cfgfile( aFilename );

    // get length
    cfgfile.SeekEnd();
    wxFileOffset size = cfgfile.Tell();
    cfgfile.Seek( 0 );

    // read data
    char*    buffer = new char[size];
    cfgfile.Read( buffer, size );

    wxString data( buffer, wxConvUTF8 );

    // parse
    ParseHotkeyConfig( data, aDescList );

    // cleanup
    delete[] buffer;
    cfgfile.Close();
    return 1;
}
コード例 #27
0
    // provider set
    void testProvSetThresholdForTwoBackends()
    {
        SelfDeletingFilePath cfgfile(SCXFileSystem::DecodePath("./testfiles/log.conf"));

        SCX_LogConfigurator subject(cfgfile);

        // Positive test to set lower case entry: should create a new file with specific entries (upper case):
        subject.Set( L"STDOUT", L"trace" );
        subject.Set( L"STDOUT:scxtest.core.common.pal.system.common.entityenumeration", L"info" );
        subject.Set( L"FILE:/myvar/opt/microsoft/scx/log/scx.log:scxtest.core.common.pal.system.common.entityenumeration", L"info" );

        std::string str = GetFileContent(cfgfile);

        // we should not see these entries
        CPPUNIT_ASSERT( str.find("HYSTERICAL")  == str.npos );
        CPPUNIT_ASSERT( str.find("/var")  == str.npos );

        // but should see these:
        CPPUNIT_ASSERT( L"TRACE" == GetLogLevel(cfgfile, L"STDOUT", L"", L"") );
        CPPUNIT_ASSERT( L"INFO" == GetLogLevel(cfgfile, L"STDOUT", L"", L"scxtest.core.common.pal.system.common.entityenumeration") );
        CPPUNIT_ASSERT( L"INFO" == GetLogLevel(cfgfile, 
                                               L"FILE", L"/myvar/opt/microsoft/scx/log/scx.log",
                                               L"scxtest.core.common.pal.system.common.entityenumeration") );
    }
コード例 #28
0
ファイル: Cspec4Cfg.cpp プロジェクト: drkjschmidt/rudolf
bool 
Cspec4Cfg::Load(CString *fname)
{
	CString line,token,value;
	CString filename;
	int tpos;

	if (fname == NULL) {

		CFileDialog TempLoader(TRUE,_T(".cfg"), NULL, 0, "Config Files (*.cfg)|*.cfg|All Files(*.*)|*.*||");
		TempLoader.m_pOFN->lpstrInitialDir=savepatharray[SAVE_PATH_CFG];

		if (TempLoader.DoModal() == IDOK)
		{
			// we have a selection
			theApp.ChangeStatusText(_T("Selection OK"));
			// savepath_cfg=TempLoader.GetFolderPath().TrimRight(_T("\\"));
			filename=TempLoader.GetPathName();
			savepatharray[SAVE_PATH_CFG]=filename;
			savepatharray[SAVE_PATH_CFG].Truncate(savepatharray[SAVE_PATH_CFG].ReverseFind('\\'));
		}
		else
		{
			// we don't have a selection
			theApp.ChangeStatusText(_T("Selection Cancel"));
			return false;
		}
	}
	else {
		filename=*fname;
	}


	try {
		//if (! cfgfile.Open(filename.GetString(),CFile::modeRead|CFile::typeText))
		//	return false;

		// Implicit open using constructor. This is not pretty
		// but makes the try / catch error handling much prettier
		CStdioFile cfgfile(filename.GetString(),CFile::modeRead|CFile::typeText);

		while (cfgfile.ReadString(line)) {
			tpos=0;
			token=line.Tokenize(_T(","),tpos);
			value=line.Tokenize(_T(","),tpos);

			if (! token.CompareNoCase(_T(TEXT_CNF_DEFSPEC)))
				lastSpectrometer=value;

			// This is an old config file but we still need to do something sensible
			if (! token.CompareNoCase(_T(TEXT_CNF_DEFGPS))) {
				lastGPSPortType="NMEA"; // @@@ This is a hack but there were no other choices at the time
				lastGPSPort=value;
				lastGPSDevice="";
				lastGPSID="";
			}

			// The 4 new values replacing it ... 
			if (! token.CompareNoCase(_T(TEXT_CNF_DEFPTP)))
				lastGPSPortType=value;
			if (! token.CompareNoCase(_T(TEXT_CNF_DEFPNM)))
				lastGPSPort=value;
			if (! token.CompareNoCase(_T(TEXT_CNF_DEFDNM)))
				lastGPSDevice=value;
			if (! token.CompareNoCase(_T(TEXT_CNF_DEFDID)))
				lastGPSID=value;

			if (! token.CompareNoCase(_T(TEXT_CNF_DEFMODE)))
			{
				cfg_runmode=atoi(value);
				// @@@ we set this here in case this gets called in program
				// but we should make sure we override this on startup ...
				theApp.setRunmode(cfg_runmode);

				// ((Cspec4Doc *)(AfxGetMainWnd()->GetActiveView()->GetDocument())->SetProgMode(theApp.runmode);
			}

			if (! token.CompareNoCase(_T(TEXT_CNF_CLRPASS)))
				passwd=value;

			if (! token.CompareNoCase(_T(TEXT_CNF_REQ_GPS)))
			{
				require_gps=true;
				if (! value.CompareNoCase(_T("false")))
					require_gps=false;
				if (! value.CompareNoCase(_T("0")))
					require_gps=false;
			}

			if (! token.CompareNoCase(_T(TEXT_CNF_REQ_SPEC)))
			{
				require_spec=true;
				if (! value.CompareNoCase(_T("false")))
					require_spec=false;
				if (! value.CompareNoCase(_T("0")))
					require_spec=false;
			}

			if (! token.CompareNoCase(_T(TEXT_CNF_ACQ_VERB)))
			{
				acq_verb=true;
				if (! value.CompareNoCase(_T("false")))
					acq_verb=false;
				if (! value.CompareNoCase(_T("0")))
					acq_verb=false;
			}

			if (! token.CompareNoCase(_T(TEXT_CNF_AS_ALL)))
			{
				specAutoSaveAll=true;
				if (! value.CompareNoCase(_T("false")))
					specAutoSaveAll=false;
				if (! value.CompareNoCase(_T("0")))
					specAutoSaveAll=false;
			}

			if (! token.CompareNoCase(_T(TEXT_CNF_AS_WARN)))
			{
				specAutoSaveWarn=true;
				if (! value.CompareNoCase(_T("false")))
					specAutoSaveWarn=false;
				if (! value.CompareNoCase(_T("0")))
					specAutoSaveWarn=false;
			}

			if (! token.CompareNoCase(_T(TEXT_CNF_AS_IMMED)))
			{
				specAutoSaveImmediate=true;
				if (! value.CompareNoCase(_T("false")))
					specAutoSaveImmediate=false;
				if (! value.CompareNoCase(_T("0")))
					specAutoSaveImmediate=false;
			}

		}

		cfgfile.Close();
	}
	catch(CFileException* pe)
	{
		char szMsg[256];
		pe->GetErrorMessage(szMsg, sizeof(szMsg));
		MessageBox(NULL, szMsg, NULL, 0);
		pe->Delete();

		return false;
	}

	return true;
}
コード例 #29
0
ファイル: Cspec4Cfg.cpp プロジェクト: drkjschmidt/rudolf
bool 
Cspec4Cfg::Save(CString *fname)
{
	CString line;
	CString filename;

	if (fname == NULL) 
	{
		CFileDialog TempLoader(FALSE,_T(".cfg"), NULL, 0, "Config Files (*.cfg)|*.cfg|All Files(*.*)|*.*||");
		TempLoader.m_pOFN->lpstrInitialDir=savepatharray[SAVE_PATH_CFG];

		if (TempLoader.DoModal() == IDOK)
		{
			// we have a selection
			theApp.ChangeStatusText(_T("Selection OK"));
			// savepath_cfg=TempLoader.GetFolderPath();
			// savepath_cfg=savepath_cfg.TrimRight(_T("\\"));
			filename=TempLoader.GetPathName();
			savepatharray[SAVE_PATH_CFG]=filename;
			savepatharray[SAVE_PATH_CFG].Truncate(savepatharray[SAVE_PATH_CFG].ReverseFind('\\'));
		}
		else
		{
			// we don't have a selection
			theApp.ChangeStatusText(_T("Selection Cancel"));
			return false;
		}
	}
	else {
		filename=*fname;
	}


	try {
		// Implicit open using constructor. This is not pretty
		// but makes the try / catch error handling much prettier
		
		//if (! cfgfile.Open(filename.GetString(),CFile::modeCreate|CFile::modeWrite|CFile::typeText))
		//	return false;
		CStdioFile cfgfile(filename.GetString(),CFile::modeCreate|CFile::modeWrite|CFile::typeText);

		line.Format(_T(TEXT_CNF_DEFSPEC ",%s\n"),lastSpectrometer.GetString());
		cfgfile.WriteString(line.GetString());

		// line.Format(_T(TEXT_CNF_DEFGPS ",%s\n"),lastGPS.GetString());
		// cfgfile.WriteString(line.GetString());
		line.Format(_T(TEXT_CNF_DEFPTP ",%s\n"),lastGPSPortType.GetString());
		cfgfile.WriteString(line.GetString());

		line.Format(_T(TEXT_CNF_DEFPNM ",%s\n"),lastGPSPort.GetString());
		cfgfile.WriteString(line.GetString());
		
		line.Format(_T(TEXT_CNF_DEFDNM ",%s\n"),lastGPSDevice.GetString());
		cfgfile.WriteString(line.GetString());
		
		line.Format(_T(TEXT_CNF_DEFDID ",%s\n"),lastGPSID.GetString());
		cfgfile.WriteString(line.GetString());

		// @@@ HACK around problem of *loading* with mode=1
		// line.Format(_T(TEXT_CNF_DEFMODE ",%d\n"),theApp.getRunmode());
		line.Format(_T(TEXT_CNF_DEFMODE ",%d\n"),0);
		cfgfile.WriteString(line.GetString());

		line.Format(_T(TEXT_CNF_CLRPASS ",%s\n"),passwd.GetString());
		cfgfile.WriteString(line.GetString());

		line.Format(_T(TEXT_CNF_REQ_GPS ",%d\n"),require_gps?1:0);
		cfgfile.WriteString(line.GetString());

		line.Format(_T(TEXT_CNF_REQ_SPEC ",%d\n"),require_spec?1:0);
		cfgfile.WriteString(line.GetString());

		line.Format(_T(TEXT_CNF_ACQ_VERB ",%d\n"),acq_verb?1:0);
		cfgfile.WriteString(line.GetString());

		line.Format(_T(TEXT_CNF_AS_IMMED ",%d\n"),specAutoSaveImmediate?1:0);
		cfgfile.WriteString(line.GetString());

		line.Format(_T(TEXT_CNF_AS_ALL ",%d\n"),specAutoSaveAll?1:0);
		cfgfile.WriteString(line.GetString());

		line.Format(_T(TEXT_CNF_AS_WARN ",%d\n"),specAutoSaveWarn?1:0);
		cfgfile.WriteString(line.GetString());

		cfgfile.Close();
	}
	catch(CFileException* pe)
	{
		char szMsg[256];
		pe->GetErrorMessage(szMsg, sizeof(szMsg));
		MessageBox(NULL, szMsg, NULL, 0);
		pe->Delete();

		return false;
	}

	return true;
}
コード例 #30
0
int main(int argc, const char *argv[]) {
	// Pick up configuration parameters
	boost::program_options::variables_map vm;

	bool bTest, bBuild, bPackage;
	bTest = bBuild = bPackage = false;
	unsigned int iLogRotationSize;
	std::string sWorkingDir;
	std::string sStageDir;
	std::string sInstallPrefix;
	std::string sPackageName;
	std::string sPackageControlFile;
	std::string sArchitecture;
	std::string sSection;
	std::string sCfgfile;
	std::string sRosVersion;
	std::string sPriority;
	std::string sLogFile;
	std::string sLogFilter;
	std::string sLogFormat;
	std::string sDebianLocation;
	std::string sDebianType;
	std::string sDBHost;
	std::string sDBDatabase;
	uint32_t uiDBPort;
	std::string sDBUser;
	std::string sDBPassword;

	boost::filesystem::path idir;
	// capture the directory from which urpackager was run.
	// we return the user to this directory when we exit.
	idir = boost::filesystem::initial_path();

	// work is run out of the users home directory
	sWorkingDir = getenv("HOME");
	if (sWorkingDir.empty()) // not a  popular linux version configuration
		sWorkingDir = getenv("USERPROFILE");
	if (sWorkingDir.empty()) {
		std::cout << "The user running this utility must have a home directory" << std::endl;
		return (ERROR_FILESYSTEM);
	}

	// If this is the first time run, configuration file and control files will not exist
	sWorkingDir += "/.urpackager";
	boost::filesystem::path wdir(sWorkingDir);
	if (!boost::filesystem::is_directory(wdir)) { // First time the utility was run by this user.
		if (!boost::filesystem::create_directory(wdir)) {
			std::cout << "Unable to write to the user's home directory" << std::endl;
			return (ERROR_FILESYSTEM);
		}
		boost::filesystem::current_path(wdir);
		boost::filesystem::create_directory("./pkgcontrol");
		boost::filesystem::create_directory("./log");
		urpackagerConfFileCreate();
		std::cout << "This is the first time you have run \"urpackager.\"" << std::endl;
		std::cout << "Edit the file '~/.urpackager/urpackager.conf'" << std::endl;
		return (EXEC_SUCCESS);
	}
	boost::filesystem::current_path(wdir);

	// get run parameters
	try {
		/** Define and parse the program options */
		boost::program_options::options_description generic("Generic Options", 255); // command line only options
		generic.add_options()
				("help,h", "Print help messages")
				("version,v", "Version 1.0.0");

		boost::program_options::options_description config("Configuration Options"); // command line or configuration file and environment
		config.add_options()
		("package", boost::program_options::value<std::string>(),
				"The name of the package for which to create a debian")
		("architecture", boost::program_options::value<std::string>(),
				"Architecture for which you wish to create a debian file")
		("section", boost::program_options::value<std::string>()->default_value("amd64"),
				"repository section for which you wish to create a debian file")
		("test", boost::program_options::value<bool>()->default_value(false),
				"prints out variables but does no work")
		("stagedir", boost::program_options::value<std::string>()->default_value("unique_path"),
				"The directory under which the debian manifest will be temporarily created")
		("installprefix", boost::program_options::value<std::string>()->default_value("/opt/magni/v4"),
				"Prefix directory into which files will be (default) installed")
		("config", boost::program_options::value<std::string>()->default_value("./urpackager.conf"),
				"The configuration file")
		("log.file", boost::program_options::value<std::string>()->default_value("./log/urpackager.log"),
				"The log file")
		("log.filter", boost::program_options::value<std::string>()->default_value("INFO"),
				"The log level")
		("log.rotationsize", boost::program_options::value<int>()->default_value(100),
				"The maximum size for the log file in MB")
		("log.format", boost::program_options::value<std::string>()->default_value("[%TimeStamp%]: %Message%"),
				"The format log messages take")
		("ros.version", boost::program_options::value<std::string>()->default_value("indigo"),
				"The version of ROS this build - appended to <run_depend> package names")
		("debian.type", boost::program_options::value<std::string>()->default_value("deb"),
				"Package either a binary (type = \"deb\") or a micro binary (type = \"udeb\")")
		("debian.location", boost::program_options::value<std::string>(),
				"Directory into which to place the debian file")
    ("database.host", boost::program_options::value<std::string>(),
	      "The host where the urpackage db is running")
    ("database.database", boost::program_options::value<std::string>(),
        "The mysql schema")
    ("database.port", boost::program_options::value<int>(),
        "The port on which the database is listening")
    ("database.user", boost::program_options::value<std::string>(),
        "The user of the database")
    ("database.password", boost::program_options::value<std::string>(),
        "Password to log into the database");
		boost::program_options::options_description hidden("Hidden"); // command line or configuration file/environment but not shown

		hidden.add_options()("administrator", boost::program_options::value<std::string>(),
				"Administration capabilities");

		boost::program_options::options_description cmdline_options;
		cmdline_options.add(generic).add(config).add(hidden);

		boost::program_options::options_description cfgfile_options;
		cfgfile_options.add(config).add(hidden);

		boost::program_options::options_description visible("Allowed options");
		visible.add(generic).add(config);

    boost::program_options::store(boost::program_options::parse_command_line(argc, argv, cmdline_options), vm); // can throw

		/* --help option */
		if (vm.count("help")) {
			std::cout << "Foo help...." << std::endl
					<< config << std::endl;
			graceful_exit(idir, EXEC_SUCCESS);
		}

		if (vm.count("version")) {
			std::cout << "urpackager Version 1.0.0" << std::endl
					<< config << std::endl;
			graceful_exit(idir, EXEC_SUCCESS);
		}

		if (vm.count("package")) {
			sPackageName = vm["package"].as<std::string>();
		}

		if (vm.count("architecture")) {
			sArchitecture = vm["architecture"].as<std::string>();
		}

		if (vm.count("section")) {
			sSection = vm["section"].as<std::string>();
		}

		if (vm.count("test")) {
			bTest = vm["test"].as<bool>();
		}

		if (vm.count("stagedir")) {
			sStageDir = vm["stagedir"].as<std::string>();
		}

		if (vm.count("installprefix")) {
			sInstallPrefix = vm["installprefix"].as<std::string>();
		}

		if (vm.count("config"))
			sCfgfile = (const std::string&) vm["config"].as<std::string>();

		std::ifstream cfgfile(sCfgfile.c_str(), std::ios::in);
		if (cfgfile.fail())
			std::cout << "Config file failed to open" << std::endl;

		boost::program_options::store(parse_config_file(cfgfile, cfgfile_options, true), vm);
		cfgfile.close();

		boost::program_options::notify(vm); // throws on error, so do after help in case
		// there are any problems
	} catch (boost::program_options::error& e) {
		std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
		graceful_exit(idir, ERROR_COMMAND_LINE);
	}

	try {
		if (vm.count("log.file"))
			sLogFile = (const std::string&) vm["log.file"].as<std::string>();

		if (vm.count("log.filter"))
			sLogFilter = (const std::string&) vm["log.filter"].as<std::string>();

		if (vm.count("log.rotationsize"))
			iLogRotationSize = (int) vm["log.rotationsize"].as<int>();

		if (vm.count("log.format"))
			sLogFormat = (const std::string&) vm["log.format"].as<std::string>();

		if (vm.count("debian.location"))
			sDebianLocation = (const std::string&) vm["debian.location"].as<std::string>();

		if (vm.count("debian.type"))
			sDebianType = (const std::string&) vm["debian.type"].as<std::string>();

		if (vm.count("ros.version"))
			sRosVersion = (const std::string&) vm["ros.version"].as<std::string>();

		if (sPackageName.empty()) {
			std::cout << "Execution of this utility requires a package name" << std::endl;
			graceful_exit(idir, ERROR_COMMAND_LINE);
		}

		if (sArchitecture.empty()) {
			sPackageControlFile = sWorkingDir + "/pkgcontrol/"
					              + sPackageName + ".pkgctl";
		} else {
			sPackageControlFile = sWorkingDir + "/pkgcontrol/" + sPackageName +
					              "." + sArchitecture + ".pkgctl";
		}
    if (vm.count("database.host"))
      sDBHost = (const std::string&) vm["database.host"].as<std::string>();

    if (vm.count("database.database"))
      sDBDatabase = (const std::string&) vm["database.database"].as<std::string>();

    if (vm.count("database.port"))
      uiDBPort = (unsigned int) vm["database.port"].as<int>();

    if (vm.count("database.user"))
      sDBUser = (const std::string&) vm["database.user"].as<std::string>();

    if (vm.count("database.password"))
      sDBPassword = (const std::string&) vm["database.password"].as<std::string>();

	} catch (std::exception& e) {
		std::cerr << "Unhandled Exception reached after applying all options: "
				<< e.what() << ", application will now exit" << std::endl;
		graceful_exit(idir, ERROR_UNHANDLED_EXCEPTION);
	}

	/* Ready to run the utility
	 *
	 */
	ur::PackageControl pc(sPackageControlFile);
	pc.readControlFile();
	pc.setStageBase(sStageDir);
	ur::PackageXML px;
	px.readFile(pc.getPackageXML());

	if(bTest) {
		graceful_exit(idir, EXEC_SUCCESS);
	}

	ur::DebianPackage pkg(pc, px,
			              sArchitecture,
					      sSection,
					      sDebianType,
					      sDebianLocation,
					      sDBHost,
					      sDBDatabase,
					      sDBUser,
					      sDBPassword,
					      uiDBPort);

	pkg.createStageDirectory();
	pkg.stageManifest();
	pkg.writeDebianControleFile();
	pkg.generateChecksums();
	pkg.generateDebianPackage();
	pkg.moveDebianPackage();
	pkg.deleteStaging();

	return (EXEC_SUCCESS);
}