Exemple #1
0
void TestPath() {
  printf("TestPath()\n");
  assert(Canonicalize("", "") == "");
  assert(Canonicalize("", "baker") == "baker");
  assert(Canonicalize("able", "") == "able");
  assert(Canonicalize("able", "baker") == "able/baker");
  assert(Canonicalize("able/", "baker") == "able/baker");
  assert(Canonicalize("baker/charlie", "#delta") == "delta");
  assert(Canonicalize("baker/charlie", "#") == "");
  assert(Canonicalize("baker/charlie", "#../external") == "../external");
  assert(Canonicalize("baker/charlie", "..") == "baker");
  assert(Canonicalize("baker/charlie", "delta") == "baker/charlie/delta");
  assert(Canonicalize("baker/charlie", "../delta") == "baker/delta");
  assert(Canonicalize("baker/charlie/", "../delta") == "baker/delta");
  assert(Canonicalize("baker/charlie", "../../delta") == "delta");
  assert(Canonicalize("baker/charlie", "../..") == "");
  assert(Canonicalize("baker/charlie", "../../../external") == "../external");
  assert(Canonicalize("baker/charlie", "#:test") == ":test");

  assert(PathJoin("a/b/c", "x/y/z") == "a/b/c/x/y/z");
  assert(PathJoin("a/b/..", "x/y/z") == "a/b/../x/y/z");
  assert(PathJoin("../..", "../x/y/z") == "../../../x/y/z");

  assert(IsAbsolute("hello") == false);
  assert(IsAbsolute("hello/there") == false);
  assert(IsAbsolute("../hello") == false);
  assert(IsAbsolute("../../hello/there") == false);
  assert(IsAbsolute("/hello") == true);
  assert(IsAbsolute("c:/hello/there") == true);
  assert(IsAbsolute("C:/hello/there") == true);
  assert(IsAbsolute("c:\\hello\\there") == true);
  assert(IsAbsolute("C:\\hello\\there") == true);
}
Exemple #2
0
bool               P3DPathName::MakeAbsolute
                                      ()
 {
  std::string                          CurrentDir;

  if (IsAbsolute())
   {
    return(true);
   }

  CurrentDir = P3DPathInfo::GetCurrentDir();

  if (CurrentDir.empty())
   {
    return(false);
   }

  P3DPathName                          WorkingDir(CurrentDir.c_str());

  WorkingDir.Normalize();

  Path = std::string(WorkingDir.c_str()) + std::string("/") + std::string(Path.c_str());

  Normalize();

  return(true);
 }
Exemple #3
0
/*
	Common
*/
String Path::Absolute(const String& path)
{
	if(IsAbsolute(path))
		return path;

	String currentDir = GetCurrentPath();
	return currentDir + sep + path;
}
Exemple #4
0
Path
MakeNormalizedAbsolute(const Path& pth, size_t len)
{
    Path res(pth);

    if(IsRelative(res))
        res = Path(FetchCurrentWorkingDirectory(len)) / res;
    res.Normalize();
    YTraceDe(Debug, "Converted path is '%s'.", string(res).c_str());
    YAssert(IsAbsolute(res), "Invalid path converted.");
    return res;
}
Exemple #5
0
	void FilePath::ConvertToAbsolute(const FilePath & basePath)
	{
		if (IsAbsolute())
		{
			return;
		}

		if (!basePath.IsAbsolute())
		{
			throw ILLEGAL_ARGUMENT_ERROR("FilePath::ConvertToAbsolute() - basePath is not absolute");
		}

		FilePath tempFilePath(basePath);
		tempFilePath.Append(*this);
		std::swap(parts_, tempFilePath.parts_);

		SetAbsolute();
	}
Exemple #6
0
std::string SetDirectory::GetRelativeFromDir(const char* filename, const char* basename)
{
    if (!filename || !filename[0]) return "";
    if (IsAbsolute(filename)) return filename; // absolute path
    std::string base = basename;
    std::string s = filename;
    // remove any ".."
    while ((s.substr(0,3)=="../" || s.substr(0,3)=="..\\") && !base.empty())
    {
        s = s.substr(3);
        base = GetParentDir(base.c_str());
    }
    if (base.empty())
        return s;
    else if (base[base.length()-1] == '/')
        return base + s;
    else
        return base + "/" + s;
}
Exemple #7
0
	void FilePath::Tokenize(FilePathTokenListener & listener) const
	{
		const ListOfParts::const_iterator end(parts_.end());

		if (IsAbsolute())
		{
			listener.OnRootDir();
		}

		for (ListOfParts::const_iterator itr(parts_.begin()); itr != end; ++itr)
		{
			if (*itr == "..")
			{
				listener.OnParentDir();
			}
			else
			{
				listener.OnPathPart(*itr);
			}
		}
	}
Exemple #8
0
bool CMaskChecker::MatchPath(cStringObj& strMask, bool bRecurse, bool bCheckAbsolute)
{
	if( !m_nNamePos && !m_nNamePos.size() )
		return false;

	bool bAbsolute = IsAbsolute(strMask);
	if( bAbsolute && !bCheckAbsolute )
		return false;

	if( m_bShort && strMask.find_first_of(L"*") != cStrObj::npos )
		return false;

	cStringPtr nMaskNamePos(strMask, strMask.find_last_of("\\/"));
	if( !*nMaskNamePos )
		nMaskNamePos = strMask;
	else
		nMaskNamePos++;

	if( m_nNamePos < nMaskNamePos )
		return false;

	if( bAbsolute ) // Маски с абсолютными путями
	{
		// Если не совпадает путь маски и объекта, то несовпадение
		if( m_strPath.compare(0, nMaskNamePos, strMask, 0, nMaskNamePos, fCOMPARE_FLAGS) )
			return false;

		// Если исключены поддиректории и есть дополнительный путь, то несовпадение
		if( !bRecurse && (tUINT)nMaskNamePos != (tUINT)m_nNamePos )
			return false;
	}
	else if( (tUINT)nMaskNamePos ) // Маски с относительными путями
	{
		// Если не найден путь маски в пути объекта, то несовпадение
		cStringPtr nMaskDirPos(m_strPath, m_strPath.find(cStringObj(strMask, 0, nMaskNamePos),
			0, cStringObj::whole, fCOMPARE_FLAGS|fSTRING_FIND_BACKWARD));

		if( !*nMaskDirPos )
			return false;

        // check subpath found to start exactly at folder begining
        if( (tUINT)nMaskDirPos != 0 && *(nMaskDirPos-1) != '\\' && *(nMaskDirPos-1) != '/' )
            return false;

		// Если исключены поддиректории и есть дополнительный путь после найденного пути маски, то несовпадение
		if( !bRecurse && (((tUINT)nMaskDirPos + (tUINT)nMaskNamePos) != (tUINT)m_nNamePos) )
			return false;
	}
	
	// Если маска "все"
	if( !*nMaskNamePos || !nMaskNamePos.compare("*") || !nMaskNamePos.compare("*.*") )
	{
		// Если имя не пустое, то совпадение
		if( !!*m_nNamePos )
			return true;
		
		// Если директория и рекурсивно, то совпадение
		if( bRecurse && (tUINT)nMaskNamePos )
			return true;
		
		// Иначе несовпадение
		return false;
	}

	// Если маска заканчивается на ".*" или на ".", и имя файла без расширения, то обрезаем маску по точку
	tDWORD nMaskSize = nMaskNamePos.size();
	if (*m_nNamePos && nMaskSize >= 2)
	{
		tDWORD nPointEndOffset = 0;
		if (nMaskNamePos[nMaskSize - 2] == L'.' && nMaskNamePos[nMaskSize - 1] == L'*')
			nPointEndOffset = 2;
		else if (nMaskNamePos[nMaskSize - 1] == L'.')
			nPointEndOffset = 1;
		if (nPointEndOffset)
		{
			tDWORD nExtPos = m_strPath.find(L".", (tUINT)m_nNamePos, cStrObj::whole, fSTRING_FIND_BACKWARD);
			if( nExtPos == cStrObj::npos )
			{
				cStrObj strNameOnlyMask;
				strNameOnlyMask.assign(strMask, (tUINT)nMaskNamePos, nMaskSize - nPointEndOffset);
				return MatchStrings(m_nNamePos, cStringPtr(strNameOnlyMask));
			}
		}
	}
	
	return MatchStrings(m_nNamePos, nMaskNamePos);
}
Exemple #9
0
void WebAddress::Combine(WebAddress Base)
{
	//Strings are hard coded to reduce code size
	String_256 sSlashDotSlash="/./";
	String_256 sSlashDotDotSlash="/../";
	
	TCHAR cSlash='/';

	//Now start the parsing.

	//If the base Web Address is empty, this Web Address does not change
	if (Base.IsEmpty())
		goto ReturnNow;

	//If this Web Address is empty, then it inherits everything from the 
	//base Web Address
	if (IsEmpty())
	{
		Absolute = Base.Absolute;

		Scheme=Base.Scheme;
		NetLoc=Base.NetLoc;
		Path=Base.Path;
		Parameters=Base.Parameters;
		Query=Base.Query;
		Fragment=Base.Fragment;
		goto ReturnNow;
	}

	//If this Web Address is absolute, it does not change
	if (IsAbsolute())
		goto ReturnNow;

	//If none of the above apply, this Web Address inherits the scheme of
	//the Base address
	Scheme=Base.Scheme;

	//If this Web Address has a net location, we need do nothing more to it.
	if (!NetLoc.IsEmpty())
		goto ReturnNow;

	//Otherwise, this Web Address inherits the Net Location of the base address.
	NetLoc=Base.NetLoc;

	//If the path of this Web Address starts with a slash, it is non-relative
	//and we need only add it on to the Net Location
	if ((*(Path))==cSlash) goto ReturnNow;


	//This is where all the loops within loops start. Hang on to your curly brackets.

	//Does this Web Address have a path?
	if (!Path.IsEmpty())
	{
		//Yes. Then the full path is given by:
		//The Base URL path up to the rightmost slash + the URL of this Web Address
		
		//This string will hold the base URL path up to the rightmost slash
		String_256 sTempPath="";
		
		//First find the rightmost slash in Base.Path
		INT32 iFound=Base.Path.ReverseFind(cSlash);
		
		//Did we find a slash?
		if (iFound>=0)
		{
			//Yes. So copy everything up to that slash into sTempPath


			Base.Path.Split(&sTempPath, NULL, iFound, TRUE);
			
			sTempPath+=Path;

			Path=sTempPath;
		}//End IF there's a slash in Base.Path

		
		//We now need to check the path for ../ and ./
		//First let's search for /./
		iFound=Path.Sub(sSlashDotSlash);

		//If we've found a /./
		while (iFound>=0)
		{
			//Then remove the ./ part of it.
			Path.Remove(iFound+1, 2);

			//And look for the next /./ to remove
			iFound=Path.Sub(sSlashDotSlash);
		}

		//Now we want to remove all occurrences of /[path segment/../
		//So first let's do a search for /../
		
		iFound=Path.Sub(sSlashDotDotSlash);

		//If we've found a /./
		while (iFound>=0)
		{
			//Then go back until we find the start of the path segment before it
			INT32 iStartOfSection=iFound-1;

			while (iStartOfSection>=0 && Path[iStartOfSection]!=cSlash)
				iStartOfSection--;

			if (iStartOfSection>=0)
			{
				//Get iStartOfSection to represent the character after the slash,
				//rather than the slash
				iStartOfSection++;

				//So if we've found something, then set a pointer to the end of that
				//section
				INT32 iEndOfSection=iFound+3;

				Path.Remove(iStartOfSection, (iEndOfSection-iStartOfSection+1));
			}
			else
				//If we found an unparsable /../, then break now before we
				//get into trouble...
				break;

			//And find the next /../
			iFound=Path.Sub(sSlashDotDotSlash);
		}	
	}
	else
	{
		//No, this Web Address doesn't have a path.
		//So it inherits the path of the base URL.
		Path=Base.Path;

		//If this Web Address has some parameters, we need do nothin more to it
		if (!Parameters.IsEmpty())
			goto ReturnNow;

		//Otherwise this Web Address inherits the parameters of the base URL
		Parameters=Base.Parameters;

		//If this Web Address has a query, we need do nothin more to it
		if (!Query.IsEmpty())
			goto ReturnNow;

		//Otherwise this Web Address inherits the parameters of the base URL
		Query=Base.Query;

		//And that's it. (Fragments are never inherited).
		//So we can return.
		goto ReturnNow;

	}//End if (!Path.IsEmpty()) else...

ReturnNow:
	//Set the "Absolute" flag to whatever it's meant to be, and return
	SetFlags();
	return;
}
Exemple #10
0
bool               P3DPathName::IsRelative
                                      () const
 {
  return(!IsAbsolute());
 }
Exemple #11
0
{
    // Compare paths, rather than inodes, to be less surprising to the user.
    // Create a temporary wxFileName to normalize the path
    wxFileName candidate_path( aFullPathAndName );

    // Edge transitions only.  This is what clears the project
    // data using the Clear() function.
    if( m_project_name.GetFullPath() != candidate_path.GetFullPath() )
    {
        Clear();            // clear the data when the project changes.

        DBG(printf( "%s: old:'%s' new:'%s'\n", __func__, TO_UTF8( GetProjectFullName() ), TO_UTF8( aFullPathAndName ) );)

        m_project_name = aFullPathAndName;

        wxASSERT( m_project_name.IsAbsolute() );

        wxASSERT( m_project_name.GetExt() == ProjectFileExtension );

        // until multiple projects are in play, set an environment variable for the
        // the project pointer.
        {
            wxString path = m_project_name.GetPath();

            wxSetEnv( PROJECT_VAR_NAME, path );
        }
    }
}


const wxString PROJECT::GetProjectFullName() const
/**
 * It Downloads all the resources, main function of concern, all the required members variables must 
 * be populated for it to work correctly
 */
void COfflineBrowser::BrowseOffline()
{
	USES_CONVERSION;

	//Delete if this directory exists, it is a disputed call, you can safely comment it out
	DeleteDirectory(m_sDir);
	//Create the directory again
	CreateDirectory(m_sDir.c_str(), NULL);
	//SaveHtml(m_sHtml);
	
	//Create HTML Document which will be hold the html that was have 
	MSHTML::IHTMLDocument2Ptr pDoc;
	HRESULT hr = CoCreateInstance(CLSID_HTMLDocument, NULL, CLSCTX_INPROC_SERVER, 
								  IID_IHTMLDocument2, (void**)&pDoc);
	if(pDoc == NULL)
		return;

	//Load HTML to Html Document
	SAFEARRAY* psa = SafeArrayCreateVector(VT_VARIANT, 0, 1);
	VARIANT *param;
	bstr_t bsData = (LPCTSTR)m_sHtml.c_str();
	hr =  SafeArrayAccessData(psa, (LPVOID*)&param);
	param->vt = VT_BSTR;
	param->bstrVal = (BSTR)bsData;
	
	//write your buffer
	hr = pDoc->write(psa);	
	//closes the document, "applying" your code  
	hr = pDoc->close();	

	//Don't forget to free the SAFEARRAY!
	SafeArrayDestroy(psa);

	//Iterate through all the elements in the document
	MSHTML::IHTMLElementCollectionPtr pCollection = pDoc->all;

	for(long a=0;a<pCollection->length;a++)
	{
		std::string sValue;
		IHTMLElementPtr pElem = pCollection->item( a );
		//If src attribute is found that means we've a resource to download
		if(GetAttribute(pElem, L"src", sValue))
		{
			//If resource URL is relative
			if(!IsAbsolute(sValue))
			{
				if(sValue[0] == '/')
					sValue = sValue.substr(1, sValue.length()-1);
				//Create directories needed to hold this resource
				//CreateDirectories(sValue, m_sDir);
				//Download the resource
				if(1)//!DownloadResource(sValue, sValue))
				{
					std::string sTemp = m_sScheme + m_sHost;
					sTemp += sValue;
					//Update src to the new src and put the original src attribute as
					//srcdump just for future references
					if(sTemp[0] == '/')
						sTemp = sTemp.substr(1, sTemp.length()-1);
					SetAttribute(pElem, L"src", sTemp);
					SetAttribute(pElem, L"srcdump", sValue);
				}
				//Unable to download the resource
				else
				{
					//Put srcdump same as src, It if for no use, I just put it to make
					//HTML DOM consistent
					SetAttribute(pElem, L"srcdump", sValue);
				}
			}
			//If resource URL is absolute
			else
			{
				std::string sTemp;
				//Make URL relative
				sTemp = TrimHostName(sValue);
				//Create directories needed to hold this resource
				//CreateDirectories(sTemp, m_sDir);
				//Dowload the resource
				if(1)//DownloadResource(sTemp, sTemp))
				{
					//Update src to the new src and put the original src attribute as
					//srcdump just for future references
					if(sTemp[0] == '/')
						sTemp = sTemp.substr(1, sTemp.length()-1);
					SetAttribute(pElem, L"src", sTemp);
					SetAttribute(pElem, L"srcdump", sValue);
				}
			}
		}
	}
	
	//Get upated HTML out of amendments we made and save it to the described directory
	MSHTML::IHTMLDocument3Ptr pDoc3 = pDoc;
	MSHTML::IHTMLElementPtr pDocElem;
	pDoc3->get_documentElement(&pDocElem);
	BSTR bstrHtml;
	pDocElem->get_outerHTML(&bstrHtml);
	std::string sNewHtml((const wchar_t*)OLE2T(bstrHtml));
	SaveHtml(sNewHtml);
}