Ejemplo n.º 1
0
//----------------------------------------------------------------------------------------
nsresult nsFileSpec::MoveToDir(const nsFileSpec& inNewParentDirectory)
//----------------------------------------------------------------------------------------
{
    // We can only copy into a directory, and (for now) can not copy entire directories
    nsresult result = NS_FILE_FAILURE;

    if (inNewParentDirectory.IsDirectory() && !IsDirectory())
    {
        char *leafname = GetLeafName();
        nsSimpleCharString destPath(inNewParentDirectory.GetCString());
        destPath += "/";
        destPath += leafname;
        nsCRT::free(leafname);

        result = NS_FILE_RESULT(CrudeFileCopy(GetCString(), (const char*)destPath));
        if (result == NS_OK)
        {
            // cast to fix const-ness
            ((nsFileSpec*)this)->Delete(PR_FALSE);
        
            *this = inNewParentDirectory + GetLeafName(); 
        }
    }
    return result;
} 
Buscador::Buscador(Estadista *estadista) : estadista(estadista) {
    this->dest = destPath();
    this->outName=dest+"salida.out";
    rtt = new RTTgenerator(dest);
    autores = new IndiceAutor(dest);
    titulos =  new IndiceTitulo(dest);
}
Ejemplo n.º 3
0
bool CompressRecursively(const wxString &path, wxZipOutputStream &zipStream, const wxString &topDir)
{
    wxFileName destPath(path);
    destPath.MakeRelativeTo(topDir);

    if (wxFileExists(path))
    {
        zipStream.PutNextEntry(destPath.GetFullPath());

        wxFFileInputStream inStream(path);
        zipStream.Write(inStream);
    }
    else if (wxDirExists(path))
    {
        zipStream.PutNextDirEntry(destPath.GetFullPath());
        wxDir dir(path);

        wxString subpath;
        if (dir.GetFirst(&subpath))
        {
            do
            {
                if (!CompressRecursively(Path::Combine(path, subpath), zipStream, topDir))
                    return false;
            } while (dir.GetNext(&subpath));
        }
    }
    return true;
}
Ejemplo n.º 4
0
void    InternUpdater::replaceUpdaterBinaryIfNeeded(void)
{
  static int attempts = 0;
  QDir downloadPath(QDir::current());

  if (!downloadPath.exists(OutDir)) return;
  downloadPath.cd(OutDir);
  if (!downloadPath.exists(UpdaterBinaryName)) return;
  QDir destPath(QDir::current());
  destPath.makeAbsolute();
  destPath.remove(UpdaterBinaryName);
  const bool moveResult =
    downloadPath.rename(downloadPath.filePath(UpdaterBinaryName),
                        destPath.path()+QDir::separator()+UpdaterBinaryName);
#ifndef QT_NO_DEBUG
  qDebug() << "[InternUpdater::replaceUpdaterBinaryIfNeeded]"
           << "moveResult:" << moveResult;
#endif
  if (moveResult == false && attempts++ < ReplaceBinaryAttempts)
    {
#ifndef QT_NO_DEBUG
      qDebug() << "[InternUpdater::replaceUpdaterBinaryIfNeeded]"
               << "replaceUpdaterBinaryIfNeeded called again in five seconds.";
      qDebug() << "Remaining attempts:" << ReplaceBinaryAttempts - attempts;
#endif
      QTimer::singleShot(5000, this, SLOT(replaceUpdaterBinaryIfNeeded()));
    }
}
Ejemplo n.º 5
0
void split(int argc, char** argv) {
    //Syntax: split [source_file] [total_parts] [destination_dir]
    if (argc >= 3) {
        QStandardItemModel* fileModel = new QStandardItemModel(1, 6);
        fileModel->deleteLater();
        SplitterCore* core = new SplitterCore(fileModel);
        core->deleteLater();
        //TODO: connect signals and implement them to show progress in terminal
        QString filePath(argv[0]);
        int parts = QString(argv[1]).toInt();
        QString destPath(argv[2]);
        QFileInfo fileinfo(filePath);
        if (fileinfo.isFile()) {
            fileModel->setData(fileModel->index(0, 0), filePath);
            fileModel->setData(fileModel->index(0, 1), destPath);
            fileModel->setData(fileModel->index(0, 2), 0);
            fileModel->setData(fileModel->index(0, 3), parts);
            fileModel->setData(fileModel->index(0, 4), fileinfo.size());
        }
        core->start();
        core->wait();
    } else {
        help(PartProcessor::kSplit);
    }
}
JNIEXPORT jlong JNICALL
Java_org_apache_subversion_javahl_SVNClient_checkout
(JNIEnv *env, jobject jthis, jstring jmoduleName, jstring jdestPath,
 jobject jrevision, jobject jpegRevision, jobject jdepth,
 jboolean jignoreExternals, jboolean jallowUnverObstructions)
{
  JNIEntry(SVNClient, checkout);
  SVNClient *cl = SVNClient::getCppObject(jthis);
  if (cl == NULL)
    {
      JNIUtil::throwError(_("bad C++ this"));
      return -1;
    }
  Revision revision(jrevision, true);
  if (JNIUtil::isExceptionThrown())
    return -1;

  Revision pegRevision(jpegRevision, true);
  if (JNIUtil::isExceptionThrown())
    return -1;

  JNIStringHolder moduleName(jmoduleName);
  if (JNIUtil::isExceptionThrown())
    return -1;

  JNIStringHolder destPath(jdestPath);
  if (JNIUtil::isExceptionThrown())
    return -1;

  return cl->checkout(moduleName, destPath, revision, pegRevision,
                      EnumMapper::toDepth(jdepth),
                      jignoreExternals ? true : false,
                      jallowUnverObstructions ? true : false);
}
Ejemplo n.º 7
0
void SaveMgrWindow::SaveListCtrl::AddSaveFromPath(wxString path)
{
	if (!wxDirExists(path))
	{
		return;
	}

	wxFileName srcPath(path);
	wxFileName destPath(Path::Combine(m_inst->GetSavesDir(), srcPath.GetFullName()));

	// Skip if the destination is the same as the source.
	if (srcPath.SameAs(destPath))
	{
		return;
	}

	if (!wxFileExists(Path::Combine(path, "level.dat")) &&
		wxMessageBox(_("This folder does not contain a level.dat file. Continue?"), 
		_("Not a valid save."), wxOK | wxCANCEL | wxCENTER, GetParent()) == wxID_CANCEL)
	{
		return;
	}

	if (wxDirExists(destPath.GetFullPath()))
	{
		int ctr = 1;
		wxString dPathName = destPath.GetName();
		while (wxDirExists(destPath.GetFullPath()) && ctr < 9000)
		{
			destPath.SetName(wxString::Format("%s (%i)", dPathName.c_str(), ctr));
			ctr++;
		}

		if (wxMessageBox(wxString::Format(
			_("There's already a save with the filename '%s'. Copy to '%s' instead?"), 
			dPathName.c_str(), destPath.GetFullName().c_str()), 
			_("File already exists."), wxOK | wxCANCEL | wxCENTER, GetParent()) == wxCANCEL)
		{
			return;
		}
	}

	if (wxFileExists(destPath.GetFullPath()))
	{
		wxLogError("Failed to copy world. File already exists.");
		return;
	}

	FileCopyTask *task = new FileCopyTask(path, destPath.GetFullPath());
	TaskProgressDialog dlg(GetParent());
	dlg.ShowModal(task);
	delete task;

	RefreshList();
}
Ejemplo n.º 8
0
void Pop3::Message::SaveAttachments (FilePath const & destFolder, SafePaths & attPaths) const
{
	for (auto_vector<Pop3::Attachment>::const_iterator att = _attachments.begin ();
		 att != _attachments.end ();
		 ++att)
	{
		// Revisit: handle the case when a file with the specified name already exists
		std::string destPath (destFolder.GetFilePath ((*att)->GetName ()));
		FileIo outFile (destPath, File::OpenAlwaysMode ());
		attPaths.Remember (destPath);

		(*att)->Save (outFile);
	}
}
Ejemplo n.º 9
0
//----------------------------------------------------------------------------------------
nsresult nsFileSpec::CopyToDir(const nsFileSpec& inParentDirectory) const
//----------------------------------------------------------------------------------------
{
    // We can only copy into a directory, and (for now) can not copy entire directories
    nsresult result = NS_FILE_FAILURE;

    if (inParentDirectory.IsDirectory() && (! IsDirectory() ) )
    {
        char *leafname = GetLeafName();
        nsSimpleCharString destPath(inParentDirectory.GetCString());
        destPath += "/";
        destPath += leafname;
        nsCRT::free(leafname);
        result = NS_FILE_RESULT(CrudeFileCopy(GetCString(), destPath));
    }
    return result;
} // nsFileSpec::CopyToDir
Ejemplo n.º 10
0
//----------------------------------------------------------------------------------------
nsresult nsFileSpec::CopyToDir(const nsFileSpec& inParentDirectory) const
//----------------------------------------------------------------------------------------
{
    // We can only copy into a directory, and (for now) can not copy entire directories
    if (inParentDirectory.IsDirectory() && (! IsDirectory() ) )
    {
        char *leafname = GetLeafName();
        nsSimpleCharString destPath(inParentDirectory.GetCString());
        destPath += "\\";
        destPath += leafname;
        nsCRT::free(leafname);
        
        // CopyFile returns non-zero if succeeds
        int copyOK = CopyFile(GetCString(), destPath, PR_TRUE);
        if (copyOK)
            return NS_OK;
    }
    return NS_FILE_FAILURE;
} // nsFileSpec::CopyToDir
JNIEXPORT void JNICALL
Java_org_apache_subversion_javahl_SVNClient_copy
(JNIEnv *env, jobject jthis, jobject jcopySources, jstring jdestPath,
 jboolean jcopyAsChild, jboolean jmakeParents, jboolean jignoreExternals,
 jobject jrevpropTable, jobject jmessage, jobject jcallback)
{
  JNIEntry(SVNClient, copy);

  SVNClient *cl = SVNClient::getCppObject(jthis);
  if (cl == NULL)
    {
      JNIUtil::throwError(_("bad C++ this"));
      return;
    }
  Array copySrcArray(jcopySources);
  if (JNIUtil::isExceptionThrown())
    return;

  CopySources copySources(copySrcArray);
  if (JNIUtil::isExceptionThrown())
    return;

  JNIStringHolder destPath(jdestPath);
  if (JNIUtil::isExceptionThrown())
    return;

  CommitMessage message(jmessage);
  if (JNIUtil::isExceptionThrown())
    return;

  RevpropTable revprops(jrevpropTable);
  if (JNIUtil::isExceptionThrown())
    return;

  CommitCallback callback(jcallback);
  cl->copy(copySources, destPath, &message, jcopyAsChild ? true : false,
           jmakeParents ? true : false, jignoreExternals ? true : false,
           revprops, jcallback ? &callback : NULL);
}
JNIEXPORT jlong JNICALL
Java_org_apache_subversion_javahl_SVNClient_doExport
(JNIEnv *env, jobject jthis, jstring jsrcPath, jstring jdestPath,
 jobject jrevision, jobject jpegRevision, jboolean jforce,
 jboolean jignoreExternals, jobject jdepth, jstring jnativeEOL)
{
  JNIEntry(SVNClient, doExport);
  SVNClient *cl = SVNClient::getCppObject(jthis);
  if (cl == NULL)
    {
      JNIUtil::throwError(_("bad C++ this"));
      return -1;
    }
  Revision revision(jrevision);
  if (JNIUtil::isExceptionThrown())
    return -1;

  Revision pegRevision(jpegRevision);
  if (JNIUtil::isExceptionThrown())
    return -1;

  JNIStringHolder srcPath(jsrcPath);
  if (JNIUtil::isExceptionThrown())
    return -1;

  JNIStringHolder destPath(jdestPath);
  if (JNIUtil::isExceptionThrown())
    return -1;

  JNIStringHolder nativeEOL(jnativeEOL);
  if (JNIUtil::isExceptionThrown())
    return -1;

  return cl->doExport(srcPath, destPath, revision, pegRevision,
                      jforce ? true : false, jignoreExternals ? true : false,
                      EnumMapper::toDepth(jdepth), nativeEOL);
}
JNIEXPORT void JNICALL
Java_org_apache_subversion_javahl_SVNClient_move
(JNIEnv *env, jobject jthis, jobject jsrcPaths, jstring jdestPath,
 jboolean jforce, jboolean jmoveAsChild, jboolean jmakeParents,
 jobject jrevpropTable, jobject jmessage, jobject jcallback)
{
  JNIEntry(SVNClient, move);

  SVNClient *cl = SVNClient::getCppObject(jthis);
  if (cl == NULL)
    {
      JNIUtil::throwError(_("bad C++ this"));
      return;
    }
  SVN::Pool tmpPool;
  StringArray srcPathArr(jsrcPaths);
  Targets srcPaths(srcPathArr, tmpPool);
  if (JNIUtil::isExceptionThrown())
    return;
  JNIStringHolder destPath(jdestPath);
  if (JNIUtil::isExceptionThrown())
    return;

  CommitMessage message(jmessage);
  if (JNIUtil::isExceptionThrown())
    return;

  RevpropTable revprops(jrevpropTable);
  if (JNIUtil::isExceptionThrown())
    return;

  CommitCallback callback(jcallback);
  cl->move(srcPaths, destPath, &message, jforce ? true : false,
           jmoveAsChild ? true : false, jmakeParents ? true : false,
           revprops, jcallback ? &callback : NULL);
}
Ejemplo n.º 14
0
/* Create an uncompressed version of the file on the local file system.
 * Note this will save zero-length files.
 */
int TskL01Extract::saveFile(const uint64_t fileId, const ArchivedFile &archivedFile)
{
    try
    {
        // If a file with this id already exists we raise an error
        std::auto_ptr<TskFile> pFile(TskServices::Instance().getFileManager().getFile(fileId));
        if (pFile.get() != NULL && pFile->exists())
        {
            std::stringstream msg;
            msg << "File id " << fileId << " already exists.";
            throw TskFileException(msg.str());
        }

        // Create a blank file
        Poco::Path destPath(TskUtilities::toUTF8(TskServices::Instance().getFileManager().getPath(fileId)));
        Poco::File destFile(destPath);
        destFile.createFile();

        // Get data from archive
        if (archivedFile.size > 0)
        {
            Poco::FileOutputStream fos(destFile.path(), std::ios::binary);

            uint64_t chunkSize = ExtractChunkSize;
            if (archivedFile.size < ExtractChunkSize)
            {
                chunkSize = archivedFile.size;
            }

            Poco::SharedPtr<char, Poco::ReferenceCounter, ArrayReleasePolicy<char> > dataBuf(new char[chunkSize]);

            uint64_t accum = 0;
            ewf::libewf_error_t *ewfError = NULL;

            // Read and save data in chunks so that we only put <= ExtractChunkSize bytes on the heap at a time
            while (accum < archivedFile.size)
            {
                ssize_t bytesRead = ewf::libewf_file_entry_read_buffer(archivedFile.entry, dataBuf, chunkSize, &ewfError);
                if (bytesRead == -1)
                {
                    std::stringstream logMessage;
                    char errorString[512];
                    errorString[0] = '\0';
                    ewf::libewf_error_backtrace_sprint(ewfError, errorString, 512);
                    logMessage << "TskL01Extract::saveFile - Error : " << errorString << std::endl;
                    LOGERROR(logMessage.str());
                    return -1;
                }
               
                fos.write(dataBuf, bytesRead);
                accum += bytesRead;
            }
            fos.close();
        }
        return 0;
    }
    catch (Poco::Exception& ex)
    {
        std::wstringstream msg;
        msg << L"TskL01Extract::saveFile - Error saving file from stream : " << ex.displayText().c_str();
        LOGERROR(msg.str());
        return -2;
    }
}
Ejemplo n.º 15
0
bool CompressFile(gcString &filePath)
{
	uint64 fileSize = UTIL::FS::getFileSize(UTIL::FS::Path(filePath, "", true));

	if (fileSize == 0)
		return false;

	gcString destPath(filePath);
	destPath += ".bz2";

	try
	{
		UTIL::FS::FileHandle fhRead(filePath.c_str(), UTIL::FS::FILE_READ);
		UTIL::FS::FileHandle fhWrite(destPath.c_str(), UTIL::FS::FILE_WRITE);

		if (fhRead.isValidFile() == false)
			return false;

		if (fhWrite.isValidFile() == false)
			return false;

		UTIL::MISC::BZ2Worker worker(UTIL::MISC::BZ2_COMPRESS);

		char buff[10*1024];

		const size_t buffsize = 10*1024;
		uint32 leftToDo = (uint32)fileSize;

		bool end = false;

		do
		{
			size_t curSize = buffsize;

			if (buffsize > leftToDo)
			{
				end = true;
				curSize = leftToDo;
			}

			fhRead.read(buff, curSize);
			leftToDo -= curSize;
			worker.write(buff, curSize, end);

			worker.doWork();
			size_t b = 0;

			do
			{
				b = buffsize;
				worker.read(buff, b);
				fhWrite.write(buff, b);
			}
			while (b > 0);
		}
		while (!end);
	}
	catch (gcException)
	{
		return false;
	}

	UTIL::FS::delFile(UTIL::FS::Path(filePath, "", true));
	filePath = destPath;

	return true;
}
Ejemplo n.º 16
0
bool DropCopyAddCommand::Execute()
{
	bool bRet = false;
	CString droppath = parser.GetVal(_T("droptarget"));
	if (CTGitPath(droppath).IsAdminDir())
		return FALSE;

	if(!CTGitPath(droppath).HasAdminDir(&g_Git.m_CurrentDir))
		return FALSE;

	int worktreePathLen = g_Git.m_CurrentDir.GetLength();
	orgPathList.RemoveAdminPaths();
	CTGitPathList copiedFiles;
	for(int nPath = 0; nPath < orgPathList.GetCount(); ++nPath)
	{
		if (orgPathList[nPath].IsEquivalentTo(CTGitPath(droppath)))
			continue;

		//copy the file to the new location
		CString name = orgPathList[nPath].GetFileOrDirectoryName();
		if (::PathFileExists(droppath + _T("\\") + name))
		{
			if (::PathIsDirectory(droppath + _T("\\") + name))
			{
				if (orgPathList[nPath].IsDirectory())
					continue;
			}

			CString strMessage;
			strMessage.Format(IDS_PROC_OVERWRITE_CONFIRM, (LPCTSTR)(droppath + _T("\\") + name));
			CString sBtn1(MAKEINTRESOURCE(IDS_PROC_OVERWRITEEXPORT_OVERWRITE));
			CString sBtn2(MAKEINTRESOURCE(IDS_PROC_OVERWRITEEXPORT_KEEP));
			CString sBtn3(MAKEINTRESOURCE(IDS_PROC_OVERWRITEEXPORT_CANCEL));
			UINT ret = CMessageBox::Show(hwndExplorer, strMessage, _T("TortoiseGit"), 2, IDI_QUESTION, sBtn1, sBtn2, sBtn3);

			if (ret == 3)
				return FALSE; //cancel the whole operation
			if (ret == 1)
			{
				if (!::CopyFile(orgPathList[nPath].GetWinPath(), droppath + _T("\\") + name, FALSE))
				{
					//the copy operation failed! Get out of here!
					ShowErrorMessage();
					return FALSE;
				}
			}
		}
		else
		{
			if (orgPathList[nPath].IsDirectory())
			{
				CString fromPath = orgPathList[nPath].GetWinPathString() + L"||";
				CString toPath = droppath + L"\\" + name + L"||";
				std::unique_ptr<TCHAR[]> fromBuf(new TCHAR[fromPath.GetLength() + 2]);
				std::unique_ptr<TCHAR[]> toBuf(new TCHAR[toPath.GetLength() + 2]);
				wcscpy_s(fromBuf.get(), fromPath.GetLength() + 2, fromPath);
				wcscpy_s(toBuf.get(), toPath.GetLength() + 2, toPath);
				CStringUtils::PipesToNulls(fromBuf.get(), fromPath.GetLength() + 2);
				CStringUtils::PipesToNulls(toBuf.get(), toPath.GetLength() + 2);

				SHFILEOPSTRUCT fileop = {0};
				fileop.wFunc = FO_COPY;
				fileop.pFrom = fromBuf.get();
				fileop.pTo = toBuf.get();
				fileop.fFlags = FOF_NO_CONNECTED_ELEMENTS | FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_NOCONFIRMMKDIR | FOF_NOCOPYSECURITYATTRIBS | FOF_SILENT;
				if (!SHFileOperation(&fileop))
				{
					// add all copied files WITH special handling for repos/submodules (folders which include a .git entry)
					CDirFileEnum finder(droppath + L"\\" + name);
					bool isDir = true;
					CString filepath;
					CString lastRepo;
					bool isRepo = false;
					while (finder.NextFile(filepath, &isDir, !isRepo)) // don't recurse into .git directories
					{
						if (!lastRepo.IsEmpty())
						{
							if (filepath.Find(lastRepo) == 0)
								continue;
							else
								lastRepo.Empty();
						}
						int pos = -1;
						if ((pos = filepath.Find(L"\\" + g_GitAdminDir.GetAdminDirName())) >= 0)
							isRepo = (pos == filepath.GetLength() - g_GitAdminDir.GetAdminDirName().GetLength() - 1);
						else
							isRepo = false;
						if (isRepo)
						{
							lastRepo = filepath.Mid(0, filepath.GetLength() - g_GitAdminDir.GetAdminDirName().GetLength());
							CString msg;
							if (!isDir)
								msg.Format(IDS_PROC_COPY_SUBMODULE, lastRepo);
							else
								msg.Format(IDS_PROC_COPY_REPOSITORY, lastRepo);
							int ret = CMessageBox::Show(hwndExplorer, msg, _T("TortoiseGit"), 1, IDI_QUESTION, CString(MAKEINTRESOURCE(IDS_DELETEBUTTON)), CString(MAKEINTRESOURCE(IDS_IGNOREBUTTON)), CString(MAKEINTRESOURCE(IDS_ABORTBUTTON)));
							if (ret == 3)
								return FALSE;
							if (ret == 1)
							{
								CTGitPath(filepath).Delete(false);
								lastRepo.Empty();
							}
							continue;
						}
						if (!isDir)
							copiedFiles.AddPath(CTGitPath(filepath.Mid(worktreePathLen + 1))); //add the new filepath
					}
				}
				continue; // do not add a directory to copiedFiles
			}
			else if (!CopyFile(orgPathList[nPath].GetWinPath(), droppath+_T("\\")+name, FALSE))
			{
				//the copy operation failed! Get out of here!
				ShowErrorMessage();
				return FALSE;
			}
		}
		CString destPath(droppath + _T("\\") + name);
		copiedFiles.AddPath(CTGitPath(destPath.Mid(worktreePathLen + 1))); //add the new filepath
	}
	//now add all the newly copied files to the working copy
	CGitProgressDlg progDlg;
	theApp.m_pMainWnd = &progDlg;
	AddProgressCommand addCommand;
	progDlg.SetCommand(&addCommand);
	addCommand.SetPathList(copiedFiles);
	progDlg.DoModal();
	bRet = !progDlg.DidErrorsOccur();

	return bRet;
}
Ejemplo n.º 17
0
Project *
App::CreateNewProject(const BMessage &settings)
{
	Project *proj = NULL;
	
	BString projectName, targetName, projectPath, templateName, pldName;
	int32 projectType, scmType;
	bool createFolder, populateProject = true;
	
	settings.FindString("name",&projectName);
	settings.FindString("target",&targetName);
	settings.FindInt32("type",&projectType);
	settings.FindString("path",&projectPath);
	settings.FindInt32("scmtype", &scmType);
	settings.FindBool("createfolder",&createFolder);
	settings.FindString("template", &templateName);
	settings.FindString("pldfile", &pldName);

	if (templateName.CountChars() > 0)
	{
		// Templates are now a directory with a TEMPLATEINFO file. All files in the
		// directory are copies, allowing for much greater flexibility than before.
		
		BString projectFileName(projectName);
		projectFileName << ".pld";
		
		DPath templatePath(gAppPath.GetFolder());
		templatePath << "Templates" << templateName;
		
		// Copy the contents of the chosen template folder to the project path
		DPath sourcePath(templatePath);
		DPath destPath(gProjectPath);
		
		if (createFolder)
		{
			destPath << projectName;
			create_directory(destPath.GetFullPath(), 0700);
		}
		
		BString wildcard("'");
		wildcard << sourcePath.GetFullPath() << "'/*";
		ShellHelper shell("cp -a ");
		shell << wildcard;
		shell.AddQuotedArg(destPath.GetFullPath());
		shell.Run();
		
		// The copy command copies *everything*, so we have to delete the
		// TEMPLATEINFO file.
		DPath templateInfo(destPath);
		templateInfo << "TEMPLATEINFO";
		BEntry infoEntry(templateInfo.GetFullPath());
		infoEntry.Remove();
		infoEntry.Unset();
		
		DPath finalPath;
		
		// Load project and set info or create one, if needed.
		
		// If the settings contain the name of a .pld project file, we'll search
		// for that first. Assuming that it exists, we'll rename that file to the
		// project name specified. If it doesn't exist or the .pld name is empty,
		// we'll create a new project with the appropriate name.
		
		// The pldname field comes from the TEMPLATEINFO file, which can designate
		// the main project file in a template. This allows a template to have
		// multiple project files, such as for the Tracker Add-on development framework
		// which has both a project file for generating the actual addon and another
		// one which is the testing framework.
		bool createProjFile = true;
		if (pldName.CountChars() > 0)
		{
			// If a .pld project file was specified in TEMPLATEINFO, check to see if
			// the file exists and rename it. If it doesn't exist, we'll create a new
			// file, and if a .pld file already exists with the intended name, we won't
			// do anything except tell the user what's happened.
			DPath oldPldNamePath(destPath);
			oldPldNamePath << pldName;
			BEntry oldPldNameEntry(oldPldNamePath.GetFullPath());
			
			DPath newPldNamePath(destPath);
			newPldNamePath << projectFileName;
			
			BEntry newPldNameEntry(newPldNamePath.GetFullPath());
			if (newPldNameEntry.Exists())
			{
				// createProjFile is false here only if there is a .pld file with the
				// user's chosen project name. If that is the case, we keep both files and
				// let the user sort it out.
				BString errMsg = B_TRANSLATE(
					"Project file '%projectname%.pld' already exists. The "
					"original file for this template is '%pldname%'. You'll need "
					"to open the project folder and figure out which one you wish to keep.");
				errMsg.ReplaceFirst("%projectname%", projectName);
				errMsg.ReplaceFirst("%pldname%", pldName);
				ShowAlert(errMsg);
				populateProject = createProjFile = false;
				
				finalPath = newPldNamePath;
			}
			else
			if (oldPldNameEntry.Exists())
			{
				oldPldNameEntry.Rename(projectFileName.String());
				populateProject = createProjFile = false;
				
				finalPath = newPldNamePath;
			}
		}
		
		if (createProjFile)
		{
			proj = Project::CreateProject(projectName.String(), targetName.String(),
									projectType, projectPath.String(), createFolder);
			if (proj)
				finalPath = proj->GetPath();
		}
		else
		{
			proj = new Project();
			if (proj->Load(finalPath.GetFullPath()) != B_OK)
			{
				delete proj;
				return NULL;
			}
		}
	}
	else
	{
		// This case is for stuff like the Quick Import feature
		proj = Project::CreateProject(projectName.String(), targetName.String(),
									projectType, projectPath.String(), createFolder);
	}
	
	if (!proj)
		return NULL;
	
	scm_t detectedSCM = DetectSCM(projectPath);
	proj->SetSourceControl(detectedSCM == SCM_NONE ? (scm_t)scmType : detectedSCM);
	
	gCurrentProject = proj;
	gProjectList->Lock();
	gProjectList->AddItem(proj);
	gProjectList->Unlock();
	
	BRect r(0,0,200,300);
	/*
	r.OffsetTo(gProjectWindowPoint);
	gProjectWindowPoint.x += 25;
	gProjectWindowPoint.y += 25;
	if (gProjectWindowPoint.x < 0)
		gProjectWindowPoint.x = 0;
	if (gProjectWindowPoint.y < 0)
		gProjectWindowPoint.y - 0;
		*/
	ProjectWindow *projwin = new ProjectWindow(r,gCurrentProject);
	projwin->Show();
	
	BEntry entry(gCurrentProject->GetPath().GetFullPath());
	if (entry.InitCheck() == B_OK)
	{
		entry_ref newprojref;
		entry.GetRef(&newprojref);
		UpdateRecentItems(newprojref);
	}
	
	if (populateProject)
	{
		entry_ref addRef;
		int32 i = 0;
		while (settings.FindRef("libs",i++,&addRef) == B_OK)
		{
			if (BEntry(&addRef).Exists())
				proj->AddLibrary(DPath(addRef).GetFullPath());
		}
		
		i = 0;
		BMessage addMsg(M_IMPORT_REFS);
		while (settings.FindRef("refs",i++,&addRef) == B_OK)
			addMsg.AddRef("refs",&addRef);
		PostToProjectWindow(&addMsg,NULL);
	}
	
	return proj;
}
Ejemplo n.º 18
0
static bool copyFiles(const char *toolsDir, const char *tmpDir, const char *globList[]) {
    SetLastError(0);
    WIN32_FIND_DATAA srcFindData;
    WIN32_FIND_DATAA destFindData;
    for (const char **glob = globList; *glob != NULL; glob++) {
        CPath globDir = CPath(*glob).dirName();

        CPath fullGlob(toolsDir);
        fullGlob.addPath(*glob);

        HANDLE srcH = FindFirstFileA(fullGlob.cstr(), &srcFindData);
        if (srcH == INVALID_HANDLE_VALUE) {
            displayLastError("Failed to list files: %s", *glob);
            return false;
        }
        do {
            // Skip directories
            if ((srcFindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0) {
                continue;
            }
            CPath srcPath(toolsDir);
            srcPath.addPath(globDir).addPath(srcFindData.cFileName);

            CPath destPath(tmpDir);
            destPath.addPath(globDir).addPath(srcFindData.cFileName);

            // Skip copy if files are likely to not have changed.
            HANDLE destH = FindFirstFileA(destPath.cstr(), &destFindData);
            if (destH != INVALID_HANDLE_VALUE) {
                // Size must be same for us to skip it.
                if (srcFindData.nFileSizeHigh == destFindData.nFileSizeHigh &&
                    srcFindData.nFileSizeLow  == destFindData.nFileSizeLow) {
                    // Creation & access times can differ. However if the dest write time
                    // is >= than the source write time, it should be the same file.
                    LARGE_INTEGER srcWriteTime;
                    LARGE_INTEGER dstWriteTime;
                    srcWriteTime.HighPart = srcFindData.ftLastWriteTime.dwHighDateTime;
                    srcWriteTime.LowPart  = srcFindData.ftLastWriteTime.dwLowDateTime;
                    dstWriteTime.HighPart = destFindData.ftLastWriteTime.dwHighDateTime;
                    dstWriteTime.LowPart  = destFindData.ftLastWriteTime.dwLowDateTime;
                    if (dstWriteTime.QuadPart >= srcWriteTime.QuadPart) {
                        FindClose(destH);
                        continue;
                    }
                }

                FindClose(destH);

                // CopyFile copies some attributes. It's common for tools to be unzipped
                // as read-only so we need to remove any r-o attribute on existing
                // files if we want a recopy to succeed.
                if ((destFindData.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0) {
                    SetFileAttributes(destPath.cstr(),
                        destFindData.dwFileAttributes ^ FILE_ATTRIBUTE_READONLY);
                }
            }

            if (!CopyFileA(srcPath.cstr(), destPath.cstr(), false /*bFailIfExists*/)) {
                FindClose(srcH);
                displayLastError("Failed to copy file: %s", destPath.cstr());
                return false;
            }
        } while (FindNextFileA(srcH, &srcFindData) != 0);
        FindClose(srcH);
    }
    return true;
}
Ejemplo n.º 19
0
bool CopyDir::copyDirAndFiles(QString srcDir, QString dstDir, QStringList *nameExcludeFilter, QStringList *nameIncludeFilter, QStringList *srcFileList, QStringList *dstFileList)
{
   if(mExitNow)
     return false;

   mutex.lock();
   if(mPause)
   {
      pauseThreads.wait(&mutex);
   }
   mutex.unlock();

   bool isFirst = false;

   if(srcFileList == NULL)
   {
      isFirst = true;
      srcFileList = new QStringList;
      dstFileList = new QStringList;
   }

   QDir rootPath(QDir::toNativeSeparators(srcDir));
   QDir destPath(QDir::toNativeSeparators(dstDir));

   rootPath.setFilter(QDir::NoDotAndDotDot | QDir::AllDirs | QDir::Files);
   QFileInfoList entryList = rootPath.entryInfoList();

   QRegExp rx;
   rx.setPatternSyntax(QRegExp::Wildcard);
   bool moveOn;
   QString dirName;

   for(int i=0; i<entryList.size(); i++)
   {
      if(mExitNow)
      {
	      return false;
      }

	   QFileInfo entry = entryList.at(i);

	   // we do exclude list checking, a lot easier to exclude a couple file types than list all of the included ones
      moveOn = false;
      for(int j=0; j<nameExcludeFilter->size(); j++)
      {
	      rx.setPattern(nameExcludeFilter->at(j));
		   QString name = entry.absoluteFilePath();
	      if(rx.exactMatch(name))
	      {
			   moveOn = true;

			   // now let's check to make sure this specific file isn't on the include list, that overrides exluded types
			   for(int k=0; k<nameIncludeFilter->size(); k++)
			   {
			      // compare the file to the include file adding the root directory (the include filter should be relative files)
			      QString filePath = QDir::toNativeSeparators(entry.filePath());
			      QString include = QDir::toNativeSeparators(mRootDir + "/" + nameIncludeFilter->at(k));
               if(include.compare(filePath) == 0)
   			   {
                     moveOn = false;
		      		  break;
			      }
   			}

			   break;
	      }
	   }

	   // if we have been matched against the exclude list then lets skip
      if(moveOn)
         continue;

      // now we copy it over
      if(entry.isDir())
      {
         dirName = entry.fileName();
         bool pathCreated = false;
         QString targetSubPath(QDir::separator() + dirName);

         if(QDir(destPath.path() + targetSubPath).exists())
         {
            pathCreated = true;
         }
         else
         {
            pathCreated = destPath.mkdir(dirName);
         }

         if(pathCreated)
         {
            copyDirAndFiles(srcDir + QDir::separator() + dirName, destPath.path() + QDir::separator() + dirName, nameExcludeFilter, nameIncludeFilter, srcFileList, dstFileList);
         }
      }
      else if(entry.isFile())
      {
         srcFileList->push_back(entry.absoluteFilePath());
         dstFileList->push_back(dstDir + QDir::separator() + entry.fileName());
      }

   }

   if(isFirst)
   {
      emit updateFileCount(srcFileList->size());

      for(int i=0; i<srcFileList->size(); i++)
      {
         if(mExitNow)
            return false;

         QFile fileEntry(srcFileList->at(i));
         fileEntry.copy(dstFileList->at(i));

         mutex.lock();
         if(mPause)
         {
            pauseThreads.wait(&mutex);
         }
         mutex.unlock();

         if(mExitNow)
            return false;

         emit updateFileProgress(i+1, QFileInfo(fileEntry.fileName()).fileName());
      }
   }

   return true;
}