Example #1
1
std::vector<IdentifierInfo> get_dcl_info(const char *decl) {
    std::vector<IdentifierInfo> identifiers;
    StringList tokens;
    StringBuffer bin(decl);
    std::string type = get_type(bin);

    while (bin.is_empty() == false) {
        tokens.clear();
        bin.trim();
        dcl(bin, tokens);
        if (bin.peekc() == ',') {
            bin.getc();
            std::string identifier = tokens[0];
            std::string datatype;
            for (int i = 1, len = tokens.size(); i < len; ++i) {
                datatype += tokens[i];
            }
            datatype += type;
            IdentifierInfo info(identifier, datatype);
            identifiers.push_back(info);
        }
        else if (bin.peekc() == ';') {
            break;
        }
        else {
            throw Exception("unknown character");
        }
    }
    std::string identifier = tokens[0];
    std::string datatype;
    for (int i = 1, len = tokens.size(); i < len; ++i) {
        datatype += tokens[i];
    }
    datatype += type;
    IdentifierInfo info(identifier, datatype);
    identifiers.push_back(info);
    return identifiers;
}
Example #2
0
bool TestKeepIf() {
    BEGIN_TEST;
    StringList list;
    const char* original[] = {"",     "foo",   "bar",    "baz",    "qux",
                              "quux", "corge", "grault", "garply", "waldo",
                              "fred", "plugh", "xyzzy",  "thud",   ""};

    const char* expected1[] = {"bar", "corge", "grault", "garply", "plugh"};

    const char* expected2[] = {"corge", "grault", "garply", "plugh"};

    const char* expected3[] = {"garply"};

    for (size_t i = 0; i < arraysize(original); ++i) {
        list.push_back(original[i]);
    }

    // Null string has no effect
    list.keep_if(nullptr);
    EXPECT_TRUE(Match(&list, original, 0, arraysize(original)));

    // Empty string matches everything
    list.keep_if("");
    EXPECT_TRUE(Match(&list, original, 0, arraysize(original)));

    // Match a string
    list.keep_if("g");
    EXPECT_TRUE(Match(&list, expected2, 0, arraysize(expected2)));

    // Match a string that would have matched elements in the original list
    list.keep_if("ar");
    EXPECT_TRUE(Match(&list, expected3, 0, arraysize(expected3)));

    // Use a string that doesn't match anything
    list.keep_if("zzz");
    EXPECT_TRUE(list.is_empty());

    // Reset and apply both matches at once with logical-or
    StringList substrs;
    substrs.push_back("g");
    substrs.push_back("ar");

    list.clear();
    for (size_t i = 0; i < arraysize(original); ++i) {
        list.push_back(original[i]);
    }
    list.keep_if_any(&substrs);
    EXPECT_TRUE(Match(&list, expected1, 0, arraysize(expected1)));

    // Reset and apply both matches at once with logical-and
    list.clear();
    for (size_t i = 0; i < arraysize(original); ++i) {
        list.push_back(original[i]);
    }
    list.keep_if_all(&substrs);
    EXPECT_TRUE(Match(&list, expected3, 0, arraysize(expected3)));

    END_TEST;
}
Example #3
0
void GetFileListRecursive(std::string dir, StringList& files, bool withQueriedDir /* = false */)
{
    std::stack<std::string> stk;

    if(withQueriedDir)
    {
        stk.push(dir);
        while(stk.size())
        {
            dir = stk.top();
            stk.pop();
            MakeSlashTerminated(dir);

            StringList li;
            GetFileList(dir.c_str(), li);
            for(std::deque<std::string>::iterator it = li.begin(); it != li.end(); ++it)
                files.push_back(dir + *it);

            li.clear();
            GetDirList(dir.c_str(), li, true);
            for(std::deque<std::string>::iterator it = li.begin(); it != li.end(); ++it)
                stk.push(dir + *it);
        }
    }
    else
    {
        std::string topdir = dir;
        MakeSlashTerminated(topdir);
        stk.push("");
        while(stk.size())
        {
            dir = stk.top();
            stk.pop();
            MakeSlashTerminated(dir);

            StringList li;
            dir = topdir + dir;
            GetFileList(dir.c_str(), li);
            for(std::deque<std::string>::iterator it = li.begin(); it != li.end(); ++it)
                files.push_back(dir + *it);

            li.clear();
            GetDirList(dir.c_str(), li, true);
            for(std::deque<std::string>::iterator it = li.begin(); it != li.end(); ++it)
                stk.push(dir + *it);
        }
    }
}
Example #4
0
/*
 * Read from file <szGlobalExcludeFunctionFileName>
 * the names of global functions, which don't need to replace.
 * In this file are function's names on each string.
 * After '#' write comments
 */
int LuaObfuscator::readAddonGlobalExcludeFunctions(const char *szGlobalExcludeFunctionFileName, StringList &FunctionsExclude)
{
	const int N = 1024;
	int res = 0;
	char buf[N];

	if (!szGlobalExcludeFunctionFileName || !szGlobalExcludeFunctionFileName[0])
		return -1;

	FILE *file = fopen(szGlobalExcludeFunctionFileName, "rt");
	if (!file)
		return -1;

	FunctionsExclude.clear();

	std::string str;
	while (feof(file) && fgets(buf, N, file)) {
		char *pName = strtrim(buf);
		if (char *p = strchr(pName, '\n'))
			*p = 0;
		if (pName[0] && pName[0] != '#') {
			str.assign(pName);
			FunctionsExclude.push_back(str);
		}
	}

	fclose(file);

	return res;
}
Example #5
0
void Options::parsePluginStringData(const std::string &str, char separator1, char separator2)
{
    StringList valueList;

    split(str, valueList, separator1);
    if (valueList.size() > 0)
    {
        StringList keyAndValue;

        for (StringList::iterator itr = valueList.begin(); itr != valueList.end(); ++itr)
        {
            split(*itr, keyAndValue, separator2);
            if (keyAndValue.size() > 1)
            {
                setPluginStringData(keyAndValue.front(), keyAndValue.back());
            }
            else if (keyAndValue.size() > 0)
            {
                setPluginStringData(keyAndValue.front(), "true");
            }

            keyAndValue.clear();
        }
    }
}
Example #6
0
size_t LuaObfuscator::readAddonTocFile(char const *szTocFileName, StringList &luaFiles) {
	char buf[300];

	if (!szTocFileName || !szTocFileName[0])
		return 0;

	FILE *fileToc = fopen(szTocFileName, "rt");
	if (!fileToc) {
		print("Couldn't open the toc file %s\n", szTocFileName);
		return 0;
	}

	luaFiles.clear();
	//files.str("");
	while (!feof(fileToc) && fgets(buf, 300, fileToc)) {
		if (!buf[0])
			continue;
		char *pFile = strtrim(buf);
		char *pFileExt = strrchr(pFile, '.');
		bool bLuaFile = false;
		if (pFileExt) {
			strlwr(pFileExt);
			bLuaFile = !strcmp(pFileExt, ".lua");
		}
		if (pFile[0] && pFile[0] != '#' &&  bLuaFile) {
			luaFiles.push_back(pFile);
		}
	}
	fclose(fileToc);

	return luaFiles.size();
}
Example #7
0
void DefaultHttpHeader::getNames(StringList& names) const {
    names.clear();

    Entry* e = head->after;
    while (e != head) {
        names.push_back(e->key);
        e = e->after;
    }
}
Example #8
0
//static
unsigned Log::tail(StringList & lout, unsigned num)
{
  lout.clear();
  unsigned i;
  p.lock();
  StringList::reverse_iterator it = p.logHistory.rbegin();
  for (i = 0; i < num && it != p.logHistory.rend(); ++i, ++it)
    lout.push_front(*it);
  p.unlock();
  return i;
}
Example #9
0
static void split(const std::string &orig, const char *delims, StringList &output)
{
    output.clear();
    std::string workBuffer = orig;
    char *rawString = &workBuffer[0];
    for(char *token = strtok(rawString, delims); token != NULL; token = strtok(NULL, delims))
    {
        if(token[0])
            output.push_back(std::string(token));
    }
}
Example #10
0
static inline StringList split2Str(const string& str, const string& separator)
{
	static StringList strs;
	strs.clear();

	size_t pos = str.find(separator);
	if (pos >= 0) {
		strs.push_back(str.substr(0, pos));
		strs.push_back(str.substr(pos + 1, str.size() - pos - 1));
	}
	return strs;
}
Example #11
0
void WikiAreaPages::createAreaPages_createCircuitsAndReferencesTableSection( String wikiDir , MindArea *area ) {
	// skip circuits for target areas - will be in region pages
	if( area -> isTargetArea() )
		return;

	// collect circuits which reference any of area regions
	MindService *ms = MindService::getService();

	StringList circuits;
	wm -> circuitsxml.getCircuitList( circuits );

	MapStringToString circuitKeys;
	for( int k = 0; k < circuits.count(); k++ ) {
		String circuitId = circuits.get( k );
		XmlCircuitInfo& info = wm -> circuitsxml.getCircuitInfo( circuitId );

		String key = createAreaPages_getCircuitKey( area , info );
		if( key.isEmpty() )
			continue;

		circuitKeys.add( key , circuitId );
	}

	// add circuits section - sorted by relevance
	StringList lines;
	for( int k = circuitKeys.count() - 1; k >= 0; k-- ) {
		String circuitId = circuitKeys.getClassByIndex( k );
		XmlCircuitInfo& info = wm -> circuitsxml.getCircuitInfo( circuitId );
		createAreaPages_getCircuitLines( info , lines );
	}

	String sectionName = "Thirdparty Circuits";
	String wikiPage = wm -> getAreaPage( area -> getAreaId() );
	wm -> updateFileSection( wikiDir , wikiPage , sectionName , lines );
	lines.clear();

	// add unique and sorted references - sorted by relevance
	MapStringToClass<MindArea> refs;
	for( int k = circuitKeys.count() - 1; k >= 0; k-- ) {
		String circuitId = circuitKeys.getClassByIndex( k );
		XmlCircuitInfo& info = wm -> circuitsxml.getCircuitInfo( circuitId );

		if( !info.reference.equals( "UNKNOWN" ) )
			if( refs.get( info.reference ) == NULL ) {
				refs.add( info.reference , area );
				lines.add( String( "  * " ) + info.reference );
			}
	}

	sectionName = "References";
	wm -> updateFileSection( wikiDir , wikiPage , sectionName , lines );
}
Example #12
0
  void File::List(StringList& rList, const std::string& sMask /*= "*" */,
                  int nAttrs /*= AttributeAnyFile | AttributeDirectory */)
  {
    rList.clear();
#ifdef WIN32
    _finddata_t stSearchData;         // search record
    intptr_t nFile = _findfirst((m_sPath + "\\" + sMask).c_str(), &stSearchData);

    if (nFile != -1)
    {
      do
      {
        if (!IsDots(stSearchData.name) &&
            (((nAttrs & AttributeDirectory) != 0)
                && (stSearchData.attrib & _A_SUBDIR) != 0) ||
            ((nAttrs & AttributeAnyFile) != 0))
        {
          rList.push_back(stSearchData.name);
        }
      }
      while (!_findnext(nFile, &stSearchData));

      _findclose(nFile);
    }
#else
    DIR* pDir = opendir(m_sPath.c_str());
    if (pDir)
    {
      struct stat stStat;
      dirent* pstDirent = NULL;
      unsigned nMask =
          ((nAttrs & AttributeDirectory) ? S_IFDIR : 0) |
          ((nAttrs & AttributeRegularFile) ? S_IFREG : 0) |
          ((nAttrs & AttributeOtherFile) ? (S_IFMT & (~(S_IFREG | S_IFDIR))) : 0);

      while((pstDirent = readdir(pDir)) != NULL)
      {
        if (!IsDots(pstDirent->d_name) &&
            !fnmatch(sMask.c_str(), pstDirent->d_name, 0) &&
            !lstat(((m_sPath + "/") + pstDirent->d_name).c_str(), &stStat) &&
            (stStat.st_mode & nMask) == (stStat.st_mode & S_IFMT))
        {
          rList.push_back(pstDirent->d_name);
        }
      }

      closedir(pDir);
    }
#endif
  }
Example #13
0
bool TestClear() {
    BEGIN_TEST;

    StringList list;
    list.push_front("bar");

    EXPECT_NONNULL(list.first());
    list.clear();
    EXPECT_NULL(list.next());
    EXPECT_NULL(list.first());
    EXPECT_EQ(list.length(), 0);

    END_TEST;
}
Example #14
0
void DefaultHttpHeader::gets(const std::string& name, StringList& headers) const {
    if (name.empty()) {
        return;
    }
    headers.clear();

    int h = hash(name);
    int i = index(h);
    Entry* e = entries[i];
    while (e != NULL) {
        if (e->hash == h && eq(name, e->key)) {
            headers.push_back(e->value);
        }
        e = e->next;
    }
}
Example #15
0
//プロパティを設定する
void XML::setProperty(Tag &tag, String source){
	StringList result;
	String name;
	String value;

	while(source != ""){
		name = "";
		value = "";
		result.clear();

		source.FrontStrip(' ');
		result = source.FrontSplit('=');
		source = result[1];
		result[0].EndStrip(' ');
		result = result[0].FrontSplit(' ');
		if(result[1] != ""){
			tag.setProperty(result[0],value);
			source = result[1]+source;
			continue;
		}
		//名前
		name = result[0];
		//値
		if(source != ""){
			source.FrontStrip('=');
			source.FrontStrip(' ');
			result = source.FrontSplit('\"');
			if(result[1] == ""){
				result = source.FrontSplit('\'');
				if(result[1] != ""){
					//シングルクォーテーションで囲われている
					result[1].FrontStrip('\'');
					result = result[1].FrontSplit('\'');
					result[1].FrontStrip('\'');
				}
			}else{
				//ダブルクォーテーションで囲われている
				result[1].FrontStrip('\"');
				result = result[1].FrontSplit('\"');
				result[1].FrontStrip('\"');
			}
			value = result[0];
			source = result[1];
		}
		tag.setProperty(name,value);
	}
}
    TEST(StringUtilsTest, join) {
        StringList components;
        ASSERT_EQ(String(""), join(components, "/"));

        components.push_back("");
        ASSERT_EQ(String(""), join(components, "/"));
        
        components.push_back("");
        ASSERT_EQ(String("/"), join(components, "/"));
        
        components.clear();
        components.push_back("asdf");
        ASSERT_EQ(String("asdf"), join(components, "/"));

        components.push_back("yo");
        ASSERT_EQ(String("asdf/yo"), join(components, "/"));
    }
Example #17
0
void WikiTractsPages::createTractsHirarchy() {

	String wikiDir = wm -> getWikiPath();
	String sectionName = wm -> getMainTractLocationSection();

	// collect section lines
	StringList lines;
	XmlTracts *tm = wm -> hmindxml.getTracts();
	MapStringToClass<XmlBrainTractSet>& tractsets = tm -> getTracts();

	for( int k = 0; k < tractsets.count(); k++ ) {
		XmlBrainTractSet& one = tractsets.getClassRefByIndex( k );
		createTracts_addTractSetLines( one , lines );
		String  wikiPage = wm -> getTractPageLink( one.id );
		wm -> updateFileSection( wikiDir , wikiPage , sectionName , lines );
		lines.clear();
	}
}
Example #18
0
    void OnRender()
    {
        Element::OnRender();

        bool scrollDown = true;
        if( GetScrollTop() > 0 && fabs( GetScrollTop() - (GetScrollHeight() - GetClientHeight()) ) > 1.0f ) {
            // do not scroll, if not at the bottom or at the top
            scrollDown = false;
        }

        size_t new_history_size = trap::Irc_HistoryTotalSize();
        if( history_size != new_history_size ) {
            // dirty
            const String br = "<br/>", e = "";
            String line, text = "";
            StringList list;

            // add IRC history lines one by one, converting
            // warsow color codes and HTML special chars to RML code
            const struct irc_chat_history_node_s *n = trap::Irc_GetHistoryHeadNode();
            while( n ) {
                list.push_back( trap::Irc_GetHistoryNodeLine( n ) );
                formatter->FormatData( line, list );

                // prepend
                text = line + ( text.Empty() ? e : br ) + text;
                n = trap::Irc_GetNextHistoryNode( n );

                list.clear();
            }

            body->SetInnerRML( text );

            UpdateLayout();

            // keep the scrollbar at the bottom
            if( scrollDown ) {
                SetScrollTop( GetScrollHeight() - GetClientHeight() );
            }

            history_size = new_history_size;
        }
    }
Example #19
0
void ClientProfileManager::loadClientProfiles(SimpleXML* aXml) {
	StringList sl;
	aXml->resetCurrentChild();
	if(aXml->findChild("ClientProfilesV2")) {
		aXml->stepIn();
		while(aXml->findChild("ClientProfile")) {
			aXml->stepIn();
			if(aXml->findChild("Name"))					{ sl.push_back(aXml->getChildData()); }	else { sl.push_back(Util::emptyString); }
			if(aXml->findChild("Version"))				{ sl.push_back(aXml->getChildData()); }	else { sl.push_back(Util::emptyString); }
			if(aXml->findChild("Tag"))					{ sl.push_back(aXml->getChildData()); }	else { sl.push_back(Util::emptyString); }
			if(aXml->findChild("ExtendedTag"))			{ sl.push_back(aXml->getChildData()); }	else { sl.push_back(Util::emptyString); }
			if(aXml->findChild("Lock"))					{ sl.push_back(aXml->getChildData()); }	else { sl.push_back(Util::emptyString); }
			if(aXml->findChild("Pk"))					{ sl.push_back(aXml->getChildData()); }	else { sl.push_back(Util::emptyString); }
			if(aXml->findChild("Supports"))				{ sl.push_back(aXml->getChildData()); }	else { sl.push_back(Util::emptyString); }
			if(aXml->findChild("TestSUR"))				{ sl.push_back(aXml->getChildData()); }	else { sl.push_back(Util::emptyString); }
			if(aXml->findChild("UserConCom"))			{ sl.push_back(aXml->getChildData()); }	else { sl.push_back(Util::emptyString); }
			if(aXml->findChild("Status"))				{ sl.push_back(aXml->getChildData()); }	else { sl.push_back(Util::emptyString); }
			if(aXml->findChild("CheatingDescription"))	{ sl.push_back(aXml->getChildData()); }	else { sl.push_back(Util::emptyString); }
			if(aXml->findChild("RawToSend"))			{ sl.push_back(aXml->getChildData()); }	else { sl.push_back(Util::emptyString); }
			//if(aXml->findChild("TagVersion"))			{ sl.push_back(aXml->getChildData()); }	else { sl.push_back(Util::emptyString); }
			if(aXml->findChild("UseExtraVersion"))		{ sl.push_back(aXml->getChildData()); }	else { sl.push_back(Util::emptyString); }
			if(aXml->findChild("CheckMismatch"))		{ sl.push_back(aXml->getChildData()); }	else { sl.push_back(Util::emptyString); }
			if(aXml->findChild("Connection"))			{ sl.push_back(aXml->getChildData()); }	else { sl.push_back(Util::emptyString); }
			if(aXml->findChild("Comment"))				{ sl.push_back(aXml->getChildData()); }	else { sl.push_back(Util::emptyString); }
			if(aXml->findChild("Recheck"))				{ sl.push_back(aXml->getChildData()); }	else { sl.push_back(Util::emptyString); }
			if(aXml->findChild("SkipExtended"))			{ sl.push_back(aXml->getChildData()); }	else { sl.push_back(Util::emptyString); }
			
			addClientProfile(sl[0], sl[1], sl[2], sl[3], sl[4], sl[5], sl[6], sl[7], sl[8], sl[9], sl[10], Util::toInt(sl[11]), 
				Util::toInt(sl[12]), Util::toInt(sl[13]), /*Util::toInt(sl[14]),*/ sl[14], sl[15], Util::toInt(sl[16]), Util::toInt(sl[17]));
			sl.clear();
			aXml->stepOut();
		}
		aXml->stepOut();
	}
	aXml->resetCurrentChild();
	if(aXml->findChild("Params")) {
		aXml->stepIn();
		while(aXml->findChild("Param")) {
			params[aXml->getChildAttrib("Name")] = aXml->getChildAttrib("RegExp");
		}
		aXml->stepOut();
	}
}
int pregetdef(string &line,string &n, string &r, StringList &a) {
    a.clear();
    if ((n=getid(line)).empty()) {
        error1("Illegal define name");
        return 0;
    }
    if (line[0]=='(') {
        line.erase(0,1);
        while(1) {
            a.push_back(getid(line));
            if (sbcneed(line,')')) break;
            if (!needcomma(line)) break;
        }
    }
    skipblanks(line);
    r=line;
    line.clear();
    return 1;
}
Example #21
0
static inline StringList stringSplit(const string& str, const string& separator)
{
	static StringList strList;
	strList.clear();

	string tempStr = str;
	size_t pos = string::npos;

	if (tempStr.find(separator) == string::npos) {
		strList.push_back(tempStr);
	} else {
		while ((pos = tempStr.find(separator)) != string::npos) {
			strList.push_back(tempStr.substr(0, pos));
			tempStr = tempStr.substr(pos + 1);
		}
		strList.push_back(tempStr);
	}

	return strList;
}
Example #22
0
void DiskDir::load()
{
    _files.clear();
    _subdirs.clear();
    // TODO: cache existing files and keep them unless they do no longer exist

    StringList li;
    GetFileList(fullname(), li);
    for(StringList::iterator it = li.begin(); it != li.end(); ++it)
    {
        DiskFile *f = new DiskFile(joinPath(fullname(), it->c_str()).c_str());
        _files[f->name()] = f;
    }

    li.clear();
    GetDirList(fullname(), li, 0);
    for(StringList::iterator it = li.begin(); it != li.end(); ++it)
    {
        // GetDirList() returns relative paths, so need to join
        Dir *d = createNew(joinPath(fullname(), it->c_str()).c_str());
        _subdirs[d->name()] = d;
    }
}
Example #23
0
TEST(OptionsTest, programargs)
{
    ProgramArgs args;

    bool falseDef, trueDef;

    args.add("falsedef", "False default", falseDef);
    args.add("truedef", "True default", trueDef, true);

    Options ops;
    ops.add("falsedef", false);
    ops.add("truedef", false);

    StringList cmdLine = ops.toCommandLine();
    args.parse(cmdLine);

    EXPECT_EQ(falseDef, false);
    EXPECT_EQ(trueDef, false);

    Options ops2;
    ops2.add("falsedef", true);
    ops2.add("truedef", true);

    cmdLine = ops2.toCommandLine();
    args.reset();
    args.parse(cmdLine);

    EXPECT_EQ(falseDef, true);
    EXPECT_EQ(trueDef, true);

    cmdLine.clear();
    args.reset();
    args.parse(cmdLine);

    EXPECT_EQ(falseDef, false);
    EXPECT_EQ(trueDef, true);
}
Example #24
0
  bool File::fileList(const String& dir, const String& file_pattern, StringList& output, bool full_path)
  {
    QDir d(dir.toQString(), file_pattern.toQString(), QDir::Name, QDir::Files);
    QFileInfoList list = d.entryInfoList();

    //clear and check if empty
    output.clear();
    if (list.empty())
    {
      return false;
    }

    //resize output
    output.resize(list.size());

    //fill output
    UInt i = 0;
    for (QFileInfoList::const_iterator it = list.constBegin(); it != list.constEnd(); ++it)
    {
      output[i++] = full_path ? it->filePath() : it->fileName();
    }

    return true;
  }
Example #25
0
void CmdLineOptions::parse(int argc, char **argv, StringList &left_overs) {
  std::unique_lock<std::mutex> l(mutex_);
  left_overs.clear();

  auto get_nice_program_name = [argv]() -> std::string {
    std::string result = std::string(argv[0]);
    // Remove everything but the command's name.
    size_t const pos = result.find_last_of("/");
    if (pos != result.npos) {
      if (pos + 1 < result.size()) {
        result = result.substr(pos);
      }
    }
    return result;
  };
  programName_ = get_nice_program_name();

  StringList listOfOptionsWithNoValue;

  for (int i(1); i < argc; ++i) {
    int const next = (i + 1) < argc ? i + 1 : -1;

    std::string arg(argv[i]);
    {
      SwitchOptList::iterator it = find_switch(arg);
      if (it != switchOptionList_.end()) {
        it->set(!it->get_default());
        continue;
      }
    }
    {
      ArgOptList::iterator it = find_arg(arg);
      if (it != argOptionList_.end()) {
        if (next != -1) {
          it->set(argv[next]);
          ++i;
          continue;
        } else {
          listOfOptionsWithNoValue.push_back(arg);
          continue;
        }
      }
    }

    // not an option :/
    left_overs.push_back(arg);
  }

  // check for the help switch.
  if (get_switch(HELP_SWITCH_NAME)) {
    print_usage(stdStream_);
    exit(EXIT_SUCCESS);
  }

  StringList listOfMissingRequiredOptions;
  StringList listOfInvalidOptions;
  for (StringOption const &option : argOptionList_) {
    if (!option.is_set() && option.is_required()) {
      listOfMissingRequiredOptions.push_back(option.name());
    } else {
      // Validate the argument
      ValidatorFunctionMap::const_iterator it = validatorFunctionMap_.find(
          option.name());
      if (it != validatorFunctionMap_.end()) {
        ValidatorFunctionList const &list(it->second);
        for (ValidatorFunction const &validator : list) {
          if (!validator(option.name(), option.get())) {
            listOfInvalidOptions.push_back(option.name());
          }
        }
      }
    }
  }

  parserResultHandler_(left_overs, listOfMissingRequiredOptions,
                       listOfOptionsWithNoValue, listOfInvalidOptions);
}
Example #26
0
/**
	\internal Does all the actual globbing.
	\author Matthias Wandel ([email protected]) http://http://www.sentex.net/~mwandel/
	\author Joshua Jensen ([email protected])

	Matthias Wandel wrote the original C algorithm, which is contained in
	his Exif Jpeg header parser at http://www.sentex.net/~mwandel/jhead/ under
	the filename MyGlob.c.  It should be noted that the MAJORITY of this
	function is his, albeit rebranded style-wise.

	I have made the following extensions:

	-	Support for ignoring directories.
	-	Perforce-style (and DJGPP-style) ... for recursion, instead of **.
	-	Automatic conversion from ...Stuff to .../*Stuff.  Allows lookup of
		files by extension, too: '....h' translates to '.../*.h'.
	-	Ability to handle forward slashes and backslashes.
	-	A minimal C++ class design.
	-	Wildcard matching not based on FindFirstFile().  Should allow greater
		control in the future and patching in of the POSIX fnmatch() function
		on systems that support it.
**/
void FileGlobBase::GlobHelper( const char* inPattern )
{
	char patternBuf[ _MAX_PATH * 2 ];
	strcpy( patternBuf, inPattern );

DoRecursion:
	char basePath[ _MAX_PATH ];
	char* basePathEndPtr = basePath;
	char* recurseAtPtr = NULL;

	// Split the path into base path and pattern to match against.
	bool hasWildcard = false;

	char* pattern;
	for ( pattern = patternBuf; *pattern != '\0'; ++pattern )
	{
		char ch = *pattern;

		// Is it a '?' ?
		if ( ch == '?' )
			hasWildcard = true;

		// Is it a '*' ?
		else if ( ch == '*' )
		{
			hasWildcard = true;

			// Is there a '**'?
			if ( pattern[ 1 ] == '*' )
			{
				// If we're just starting the pattern or the characters immediately
				// preceding the pattern are a drive letter ':' or a directory path
				// '/', then set up the internals for later recursion.
				if ( pattern == patternBuf  ||  pattern[ -1 ] == '/'  ||
					pattern[ -1 ] == ':')
				{
					char ch2 = pattern[ 2 ];
					if ( ch2 == '/' )
					{
						recurseAtPtr = pattern;
						memcpy(pattern, pattern + 3, strlen( pattern ) - 2 );
					}
					else if ( ch2 == '\0' )
					{
						recurseAtPtr = pattern;
						*pattern = '\0';
					}
				}
			}
		}

		// Is there a '/' or ':' in the pattern at this location?
		if ( ch == '/'  ||  ch == ':' )
		{
			if ( hasWildcard )
				break;
			basePathEndPtr = &basePath[ pattern - patternBuf + 1 ];
		}
	}

	// If there is no wildcard this time, then just add the current file and
	// get out of here.
	if ( !hasWildcard )
	{
		// This should refer to a file.
		FoundMatch( patternBuf );
		return;
	}

	// Did we make it to the end of the pattern?  If so, we should match files,
	// since there were no slashes encountered.
	bool matchFiles = *pattern == '\0';

	// Copy the directory down.
	size_t basePathLen = basePathEndPtr - basePath;
	strncpy( basePath, patternBuf, basePathLen );

	// Copy the wildcard matching string.
	char matchPattern[ _MAX_PATH ];
	size_t matchLen = ( pattern - patternBuf ) - basePathLen;
	strncpy( matchPattern, patternBuf + basePathLen, matchLen + 1 );
	if ( matchPattern[ matchLen ] == '/' )
		matchPattern[ matchLen ] = 0;

	StringList fileList;

	// Do the file search with *.* in the directory specified in basePattern.
	strcpy( basePathEndPtr, "*.*" );

	// Start the find.
	WIN32_FIND_DATA fd;
	HANDLE handle = FindFirstFile( basePath, &fd );

	// Clear out the *.* so we can use the original basePattern string.
	*basePathEndPtr = 0;

	// Any files found?
	if ( handle != INVALID_HANDLE_VALUE )
	{
		for ( ;; )
		{
			// Is the file a directory?
			if ( ( fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )  &&  !matchFiles )
			{
				// Do a wildcard match.
				if ( WildMatch( matchPattern, fd.cFileName, false ) )
				{
					// It matched.  Let's see if the file should be ignored.
					bool ignore = false;

					// Knock out "." or ".." if they haven't already been.
					size_t len = strlen( fd.cFileName );
					fd.cFileName[ len ] = '/';
					fd.cFileName[ len + 1 ] = '\0';

					// See if this is a directory to ignore.
					ignore = MatchIgnorePattern( fd.cFileName );

					fd.cFileName[ len ] = 0;

					// Should this file be ignored?
					if ( !ignore )
					{
						// Nope.  Add it to the linked list.
						fileList.push_back( fd.cFileName );
					}
				}
			}
			else if ( !( fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )  &&  matchFiles )
			{
				// Do a wildcard match.
				if ( WildMatch( matchPattern, fd.cFileName, false ) )
				{
					// It matched.  Let's see if the file should be ignored.
					bool ignore = MatchIgnorePattern( fd.cFileName );

					// Is this pattern exclusive?
					if ( !ignore  &&  m_exclusiveFilePatterns.begin() != m_exclusiveFilePatterns.end() )
					{
						ignore = !MatchExclusivePattern( fd.cFileName );
					}

					// Should this file be ignored?
					if ( !ignore )
					{
						// Nope.  Add it to the linked list.
						fileList.push_back( fd.cFileName );
					}
				}
			}

			// Look up the next file.
			if ( !FindNextFile( handle, &fd ) )
				break;
		}

		// Close down the file find handle.
		FindClose( handle );
	}

	// Sort the list.
	fileList.sort();

	// Iterate the file list and either recurse or add the file as a found
	// file.
	if ( !matchFiles )
	{
		for ( StringList::iterator it = fileList.begin(); it != fileList.end(); ++it )
		{
			char combinedName[ _MAX_PATH * 2 ];

			// Need more directories.
			CatPath( combinedName, basePath, (*it).c_str() );
			strcat( combinedName, pattern );
			GlobHelper( combinedName );
		}
	}
	else // if ( !matchFiles )
	{
		for ( StringList::iterator it = fileList.begin(); it != fileList.end(); ++it )
		{
			char combinedName[ _MAX_PATH * 2 ];
			CatPath( combinedName, basePath, (*it).c_str());
			FoundMatch( combinedName );
		}
	}

	// Clear out the file list, so the goto statement below can recurse
	// internally.
	fileList.clear();

	// Do we need to recurse?
	if ( !recurseAtPtr )
		return;

	// Copy in the new recursive pattern to match.
	strcpy( matchPattern, recurseAtPtr );
	strcpy( recurseAtPtr, "*/**/" );
	strcat( patternBuf, matchPattern );

	// As this function context is no longer needed, we can just go back
	// to the top of it to avoid adding another context on the stack.
	goto DoRecursion;
}
Example #27
0
/**
	@todo Evaluate performance of compile and run of various compilers
*/
int main(int argc, const char * const argv[]) {
	StringList				testsToRun;
	Dictionary				headerCoverage, testMetrics;

	loadExpectations(headerCoverage, testMetrics, testsToRun);
	for(int arg= 1; arg < argc; ++arg) {
		if(std::string("debug") == argv[arg]) {
			gDebugging= true;
		} else if(std::string("list") == argv[arg]) {
			testsToRun.clear();
			for(StringList::iterator test= testsToRun.begin(); test != testsToRun.end(); ++test) {
				printf("%s\n", test->c_str());
			}
		} else if(std::string("verbose") == argv[arg]) {
			gVerbose= true;
		} else {
			bool	found= testMetrics.count(argv[arg]) > 0;

			if(found) {
				if(testsToRun.size() > static_cast<unsigned int>(arg)) {
					testsToRun.clear();
				}
				testsToRun.push_back(argv[arg]);
			} else {
				printf("Test not found: %s\n", argv[arg]);
			}
		}
	}
	try {
		std::string	results;
		StringList	headers;

		exec::execute("mkdir -p bin/tests bin/logs", results);
		if(results != "") {
			printf("WARNING: mkdir '%s'\n", results.c_str());
		}
		exec::execute("rm -Rf bin/logs/* bin/tests/*", results);
		if(results != "") {
			printf("WARNING: rm '%s'\n", results.c_str());
		}
		for(StringList::iterator test= testsToRun.begin(); test != testsToRun.end(); ++test) {
			runTest(*test, testMetrics[*test]);
		}
		if(testsToRun.size() > 0) {
			printf("Examining overall coverage ...\n");
			exec::execute("ls *.h", results);
			split(results, '\n', headers);
			runNoResultsExpected("cat bin/logs/*_trace_run.log | grep /os/ | sort | uniq > bin/logs/all_trace.log", "Combining coverage");
			for(StringList::iterator header= headers.begin(); header != headers.end(); ++header) {
				uint32_t	coverage;
				bool		found= headerCoverage.count(*header) > 0;
				int			value= found ? atoi(headerCoverage[*header].c_str()) : 0;

				coverage= runIntegerExpected("cat bin/logs/all_trace.log | grep ../os/"+*header+": | wc -l");
				if(found) {
					if(value != static_cast<int>(coverage)) {
						printf("%20s\tCoverage: %4d Expected: %4d\n", header->c_str(), coverage, value);
					}
				} else {
					printf("WARNING: No data for header %s with coverage %d\n", header->c_str(), coverage);
				}
			}
		}
	} catch(const std::exception &exception) {
		printf("EXCEPTION: %s\n", exception.what());
	}
	return 0;
}
Example #28
0
 virtual void GetProvidersList(StringList& rlsProvidersList)
 {
   rlsProvidersList.clear();
   rlsProvidersList.push_back("staff.das.MySql");
 }
Example #29
0
void LangManager::getSupportedLanguageNames(StringList& stringList) const
{
  stringList.clear();
  stringList.push_back("eng");
  stringList.push_back("rus");
}
const string LdapTools::getFreeIp(const NetworkRange* range) {
	string retval = "";
	set<long> ips;

	string base = "ou=dhcp,ou=networks,ou=virtualization,ou=services,";
	base.append(Config::getInstance()->getLdapBaseDn());
	string filter = "(&(objectClass=sstVirtualizationNetworkRange)(cn=";
	filter.append(range->getRange()).append("))");
	StringList attrs = StringList();
	attrs.add("cn");
	SYSLOGLOGGER(logDEBUG) << "getFreeIp: " << base << "; " << filter;
	LDAPSearchResults* entries = lc->search(base, LDAPConnection::SEARCH_SUB, filter, attrs);
	if (NULL != entries) {
		LDAPEntry* entry = entries->getNext();
		if (NULL != entry) {
			string dn = entry->getDN();
			SYSLOGLOGGER(logDEBUG) << "rangeDN: " << dn;
			size_t pos = dn.find("ou=ranges,");
			dn = dn.substr(pos + 10);
			SYSLOGLOGGER(logDEBUG) << "subnetDN: " << dn;

			attrs.clear();
			attrs.add("dhcpOption");
			LDAPSearchResults* entries2 = lc->search(dn, LDAPConnection::SEARCH_SUB, "objectClass=dhcpOptions", attrs);
			if (NULL != entries2) {
				LDAPEntry* entry2 = entries2->getNext();
//				while (entry2 != 0) {
//					std::cout << "dn: " << entry2->getDN() << endl;
//					const LDAPAttributeList* attrs = entry2->getAttributes();
//					LDAPAttributeList::const_iterator it = attrs->begin();
//					for (; it != attrs->end(); it++) {
//						LDAPAttribute attr = *it;
//						std::cout << attr.getName() << "(";
//						std::cout << attr.getNumValues() << "): ";
//						StringList values = attr.getValues();
//						StringList::const_iterator it2 = values.begin();
//						for (; it2 != values.end(); it2++) {
//
//							std::cout << *it2 << "; ";
//						}
//						std::cout << std::endl;
//					}
//					std::cout << endl;
//					delete entry2;
//					entry2 = entries->getNext();
//				}

				if (NULL != entry2) {
					const LDAPAttribute* attribute = entry2->getAttributeByName("dhcpOption");
					if (NULL != attribute) {
						StringList values = attribute->getValues();
						for (StringList::const_iterator it = values.begin(); it != values.end(); it++) {
							string value = *it;
							if (0 == value.find("routers ")) {
								SYSLOGLOGGER(logDEBUG) << value;
								ips.insert(NetworkRange::ip2long(value.substr(8)));
								break;
							}
						}
					}
					delete entry2;
				}
			}

			dn = "ou=virtual machines," + dn;
			SYSLOGLOGGER(logDEBUG) << "search IPs DN: " << dn;

			filter = "(objectClass=dhcpHost)";
			attrs.clear();
			attrs.add("dhcpStatements");
			LDAPSearchResults* entries3 = lc->search(dn, LDAPConnection::SEARCH_SUB, filter, attrs);
			if (NULL != entries3) {
				LDAPEntry* entry3 = entries3->getNext();
				while (NULL != entry3) {
					StringList values = entry3->getAttributeByName("dhcpStatements")->getValues();
					for (StringList::const_iterator it = values.begin(); it != values.end(); it++) {
						string value = *it;
						if (0 == value.find("fixed-address ")) {
							SYSLOGLOGGER(logDEBUG) << value << "; " << (NetworkRange::ip2long(value.substr(14)));
							ips.insert(NetworkRange::ip2long(value.substr(14)));
						}
					}

					delete entry3;
					entry3 = entries3->getNext();
				}
			}
			delete entry;
		}
	}
	long hostmin = NetworkRange::ip2long(range->getHostMin());
	long hostmax = NetworkRange::ip2long(range->getHostMax());
	for (long i = hostmin; i <= hostmax; i++) {
		SYSLOGLOGGER(logDEBUG) << i << ": " << (NetworkRange::long2ip(i));
		if (ips.end() == ips.find(i)) {
			retval = NetworkRange::long2ip(i);
			break;
		}
	}

	return retval;
}