Пример #1
0
void
URI::setupURI(const std::string& u, bool absolute)
{
  if (u.find("file://") != 0 && u.find("file:") != 0 && u.find("http://") != 0)
    {
      // must be a plain pathname
      uri = "file:" + (absolute ? getAbsolutePath(u) : u);
    }
  else if (u.find("file://") == 0) // this needs a special massage
    {
      std::string tmp = u.substr(7);
      uri = "file:" + (absolute ? getAbsolutePath(tmp) : tmp);
    }
  else if (u.find("file:") == 0)
    {
      if (absolute)
	{
	  uri = "file:" + getAbsolutePath(u.substr(5));
	}
      else // use uri as is
	{
	  uri = u;
	}
    }
  else // use non-local URI as is
    {
      uri = u;
    }
}
Пример #2
0
void ofPackageManager::generateDatabaseEntryFile()
{
	ofJson dataBaseEntryJson;

	if (hasPackageFile(getAbsolutePath(_cwdPath)))
	{
		ofFile packageFile(getAbsolutePath(_cwdPath));
		ofJson packageJson;
		packageJson << packageFile;

		dataBaseEntryJson["name"] = packageJson["name"];
		dataBaseEntryJson["author"] = packageJson["author"];
		dataBaseEntryJson["url"] = packageJson["url"];
		dataBaseEntryJson["cloneUrl"] = packageJson["cloneUrl"];
		dataBaseEntryJson["license"] = packageJson["license"];
		dataBaseEntryJson["type"] = packageJson["type"];
	}
	else
	{
		dataBaseEntryJson["name"] = getStringAnswer("package name?");
		dataBaseEntryJson["author"] = getStringAnswer("author?");
		dataBaseEntryJson["url"] = getStringAnswer("url?");
		dataBaseEntryJson["cloneUrl"] = getStringAnswer("cloneUrl?");
		dataBaseEntryJson["license"] = getStringAnswer("license?");
		dataBaseEntryJson["type"] = getOptionAnswer("type", {"app", "addon"});
	}

	std::string name = dataBaseEntryJson["name"];
	ofFile dataBaseEntryFile(ofFilePath::addTrailingSlash(getAbsolutePath(_cwdPath)) + name + ".json", ofFile::ReadWrite);
	if (!dataBaseEntryFile.exists())
	{
		dataBaseEntryFile.create();
	}
	dataBaseEntryFile << dataBaseEntryJson.dump(4);
}
Пример #3
0
int LocalPackage::fill_filelist(PACKAGE *package, bool)
{
	if (!package) package=&data;
	//mDebug("fill_filelist start");
	// Retrieving regular files
	// For setup mode, we can try to enable cached filelists
	vector<string> file_names;
	string fname;
	bool fname_temp = false;
	if (setupMode && FileExists(getAbsolutePath(getDirectory(filename))+"/.fcache/" + getFilename(filename) + "/flist")) {
		fname = getAbsolutePath(getDirectory(filename))+"/.fcache/" + getFilename(filename) + "/flist";
	}
	else {
		fname = get_tmp_file();
		fname_temp = true;
		system("tar tf "+filename+" --exclude install " +" > "+fname + " 2>/dev/null");
	}
	// Parsing file list
	file_names=ReadFileStrings(fname);
	if (fname_temp) unlink(fname.c_str());
	if (file_names.size()>2) file_names.erase(file_names.begin(), file_names.begin()+2);
	else {
		mWarning("Empty file list in package " + package->get_name());
		file_names.clear();
	}
	package->set_files(file_names);
	// Retrieving symlinks (from doinst.sh).
	string dt;
	bool dt_temp=false;
	// Extracting file to the temp dir
	if (setupMode && FileExists(getAbsolutePath(getDirectory(filename))+"/.fcache/" + getFilename(filename) + "/doinst.sh")) {
		dt = getAbsolutePath(getDirectory(filename))+"/.fcache/" + getFilename(filename) + "/doinst.sh";
	}
	else if (!setupMode || !FileExists(getAbsolutePath(getDirectory(filename))+"/.fcache/" + getFilename(filename) + "/flist")) { // Assuming that doinst.sh isn't present if flist is cached
		dt = get_tmp_file();
		extractFromTgz(filename, "install/doinst.sh", dt);
		dt_temp = true;
	}

	
	if (!dt.empty() && FileExists(dt)) {
		string lnfname=get_tmp_file();
		string sed_cmd = "sed -n 's,^( *cd \\([^ ;][^ ;]*\\) *; *rm -rf \\([^ )][^ )]*\\) *) *$,\\1/\\2,p' < ";
		sed_cmd += dt + " > " + lnfname;
		system(sed_cmd);
		vector<string>link_names=ReadFileStrings(lnfname);
		for (size_t i=0; i<link_names.size(); ++i) {
			if (!link_names[i].empty()) package->get_files_ptr()->push_back(link_names[i]);
		}
		if (dt_temp) unlink(dt.c_str());
		unlink(lnfname.c_str());
	}

	delete_tmp_files();
	return 0;
}
Пример #4
0
void FSDir::readContent()
{
	freeContent();
	std::string command = "ls -lh";

	command += " " + getAbsolutePath() + "/";
	command += " | tail -n +2 ";
	command += " | ";
	command += AWK;

	std::string ls = exec(command);

	std::istringstream iss(ls);
	std::string line;

	while ( line.clear(), getline(iss, line) )
	{
		std::istringstream linestream(line);
		std::string filename;
		std::string date; 
		std::string size;
		std::string owner;
		std::string perms;

		getline(linestream, filename, '#');
		getline(linestream, date, '#');
		getline(linestream, size, '#');
		getline(linestream, owner, '#');
		getline(linestream, perms);

		if ( ! hidden && filename[0] == '.' )
			continue;

		if ( perms[0] == 'd' )
		{
			FSDir * d = new FSDir( getAbsolutePath() + PATH_SEPARATOR + filename);
			d->setAttrs(date, owner, size, perms);
			content.push_back((FSObject*) d);
		}
		else if ( perms[0] == 'l' )
		{
			FSSymlink * d = new FSSymlink( getAbsolutePath() + PATH_SEPARATOR + filename);
			d->setAttrs(date, owner, size, perms);
			content.push_back((FSObject*) d);
		}
		else
		{
			FSFile * f = new FSFile(getAbsolutePath() + PATH_SEPARATOR + filename);
			f->setAttrs(date, owner, size, perms);
			content.push_back((FSObject*) f);
		}
	}

	std::sort(content.begin(), content.end(), directoriesFirst);
}
Пример #5
0
int handleRename(const char *fpath, RenameOperation *renameop) {
    char foldpath[PATH_MAX];
    char fnewpath[PATH_MAX];

    getAbsolutePath(foldpath, config.rootdir, renameop->oldpath);
    getAbsolutePath(fnewpath, config.rootdir, renameop->newpath);

    if (rename(foldpath, fnewpath) == -1) {
        errnoMsg(LOG_ERR, "Could not rename file %s", fpath);
        return -1;
    }

    return 0;
}
Пример #6
0
FileInputSource::FileInputSource(const String *basePath, FileInputSource *base){
  bool prefix = true;
  if (basePath->startsWith(DString("file://"))){
    baseLocation = new SString(basePath, 7, -1);
  }else if (basePath->startsWith(DString("file:/"))){
    baseLocation = new SString(basePath, 6, -1);
  }else if (basePath->startsWith(DString("file:"))){
    baseLocation = new SString(basePath, 5, -1);
  }else{
    if (isRelative(basePath) && base != null)
      baseLocation = getAbsolutePath(base->getLocation(), basePath);
    else
      baseLocation = new SString(basePath);
    prefix = false;
  };
#if defined _WIN32
   // replace the environment variables to their values
  size_t i=ExpandEnvironmentStrings(baseLocation->getTChars(),NULL,0);
  TCHAR *temp = new TCHAR[i];
  ExpandEnvironmentStrings(baseLocation->getTChars(),temp,static_cast<DWORD>(i));
  delete baseLocation;
  baseLocation = new SString(temp);
  delete[] temp;
#endif
  if(prefix && (baseLocation->indexOf(':') == -1 || baseLocation->indexOf(':') > 10) && !baseLocation->startsWith(DString("/"))){
    StringBuffer *n_baseLocation = new StringBuffer();
    n_baseLocation->append(DString("/")).append(baseLocation);
    delete baseLocation;
    baseLocation = n_baseLocation;
  }
  stream = null;
};
Пример #7
0
int hdfsUtime(hdfsFS fs, const char* path, tTime mtime, tTime atime)
{
    char *url = NULL, *absPath = NULL;
    struct Response *resp = NULL;
    int ret = 0;

    if (fs == NULL || path == NULL) {
        ret = EINVAL;
        goto done;
    }
    ret = getAbsolutePath(fs, path, &absPath);
    if (ret) {
        goto done;
    }
   
    ret = createUrlForUTIMES(fs->nn, fs->port, absPath, mtime, atime,
                             fs->userName, &url);
    if (ret) {
        goto done;
    }
    ret = launchUTIMES(url, &resp);
    if (ret) {
        goto done;
    }
    ret = parseUTIMES(resp->header->content, resp->body->content);
done:
    freeResponse(resp);
    free(absPath);
    free(url);
    if (ret) {
        errno = ret;
        return -1;
    }
    return 0;
}
Пример #8
0
int hdfsDelete(hdfsFS fs, const char* path, int recursive)
{
    char *url = NULL, *absPath = NULL;
    struct Response *resp = NULL;
    int ret = 0;

    if (fs == NULL || path == NULL) {
        ret = EINVAL;
        goto done;
    }
    ret = getAbsolutePath(fs, path, &absPath);
    if (ret) {
        goto done;
    }
    
    ret = createUrlForDELETE(fs->nn, fs->port, absPath,
                             recursive, fs->userName, &url);
    if (ret) {
        goto done;
    }
    ret = launchDELETE(url, &resp);
    if (ret) {
        goto done;
    }
    ret = parseDELETE(resp->body->content);
done:
    freeResponse(resp);
    free(absPath);
    free(url);
    if (ret) {
        errno = ret;
        return -1;
    }
    return 0;
}
Пример #9
0
int hdfsSetReplication(hdfsFS fs, const char* path, int16_t replication)
{
    char *url = NULL, *absPath = NULL;
    struct Response *resp = NULL;
    int ret = 0;

    if (fs == NULL || path == NULL) {
        ret = EINVAL;
        goto done;
    }
    ret = getAbsolutePath(fs, path, &absPath);
    if (ret) {
        goto done;
    }

    ret = createUrlForSETREPLICATION(fs->nn, fs->port, absPath,
                                     replication, fs->userName, &url);
    if (ret) {
        goto done;
    }
    ret = launchSETREPLICATION(url, &resp);
    if (ret) {
        goto done;
    }
    ret = parseSETREPLICATION(resp->body->content);
done:
    freeResponse(resp);
    free(absPath);
    free(url);
    if (ret) {
        errno = ret;
        return -1;
    }
    return 0;
}
Пример #10
0
int hdfsChown(hdfsFS fs, const char* path, const char *owner, const char *group)
{
    int ret = 0;
    char *absPath = NULL, *url = NULL;
    struct Response *resp = NULL;

    if (fs == NULL || path == NULL) {
        ret = EINVAL;
        goto done;
    }
    
    ret = getAbsolutePath(fs, path, &absPath);
    if (ret) {
        goto done;
    }
    ret = createUrlForCHOWN(fs->nn, fs->port, absPath,
                            owner, group, fs->userName, &url);
    if (ret) {
        goto done;
    }
    ret = launchCHOWN(url, &resp);
    if (ret) {
        goto done;
    }
    ret = parseCHOWN(resp->header->content, resp->body->content);
done:
    freeResponse(resp);
    free(absPath);
    free(url);
    if (ret) {
        errno = ret;
        return -1;
    }
    return 0;
}
Пример #11
0
int hdfsChmod(hdfsFS fs, const char* path, short mode)
{
    char *absPath = NULL, *url = NULL;
    struct Response *resp = NULL;
    int ret = 0;

    if (fs == NULL || path == NULL) {
        ret = EINVAL;
        goto done;
    }
    ret = getAbsolutePath(fs, path, &absPath);
    if (ret) {
        goto done;
    }
    ret = createUrlForCHMOD(fs->nn, fs->port, absPath, (int) mode,
                            fs->userName, &url);
    if (ret) {
        goto done;
    }
    ret = launchCHMOD(url, &resp);
    if (ret) {
        goto done;
    }
    ret = parseCHMOD(resp->header->content, resp->body->content);
done:
    freeResponse(resp);
    free(absPath);
    free(url);
    if (ret) {
        errno = ret;
        return -1;
    }
    return 0;
}
Пример #12
0
ClangTool::ClangTool(const CompilationDatabase &Compilations,
                     ArrayRef<std::string> SourcePaths)
    : Files(new FileManager(FileSystemOptions())), DiagConsumer(NULL) {
  ArgsAdjusters.push_back(new ClangStripOutputAdjuster());
  ArgsAdjusters.push_back(new ClangSyntaxOnlyAdjuster());
  for (const auto &SourcePath : SourcePaths) {
    std::string File(getAbsolutePath(SourcePath));

    std::vector<CompileCommand> CompileCommandsForFile =
      Compilations.getCompileCommands(File);
    if (!CompileCommandsForFile.empty()) {
      for (CompileCommand &CompileCommand : CompileCommandsForFile) {
        CompileCommands.push_back(
            std::make_pair(File, std::move(CompileCommand)));
      }
    } else {
      // FIXME: There are two use cases here: doing a fuzzy
      // "find . -name '*.cc' |xargs tool" match, where as a user I don't care
      // about the .cc files that were not found, and the use case where I
      // specify all files I want to run over explicitly, where this should
      // be an error. We'll want to add an option for this.
      llvm::errs() << "Skipping " << File << ". Compile command not found.\n";
    }
  }
}
Пример #13
0
string runLs(session* ses, list<string> args) {
    FILE *fp;

    char path[1035];

    string cmd("ls ");
    cmd += getAbsolutePath(ses->currentDir);
    cmd +=  " -A -n | tail -n+2";

    cerr << "runLs: " << cmd << "\n";

    fp = popen(cmd.c_str(), "r");
    if (fp == NULL) {
        cerr << "Failed to run command\n";
    }

    string result("");
    /* Read the output a line at a time - output it. */
    while (fgets(path, sizeof(path)-1, fp) != NULL) {
        result += path;
    }

    pclose(fp);

    return result;
}
Пример #14
0
//! opens a file for read access
IReadFile* CFileSystem::createAndOpenFile(const c8* filename)
{
	IReadFile* file = 0;
	u32 i;

	for ( i=0; i<ZipFileSystems.size(); ++i)
	{
		file = ZipFileSystems[i]->openFile(filename);
		if (file)
			return file;
	}

	for ( i = 0; i<PakFileSystems.size(); ++i)
	{
		file = PakFileSystems[i]->openFile(filename);
		if (file)
			return file;
	}

	for ( i = 0; i<UnZipFileSystems.size(); ++i)
	{
		file = UnZipFileSystems[i]->openFile(filename);
		if (file)
			return file;
	}

	// Create the file using an absolute path so that it matches
	// the scheme used by CNullDriver::getTexture().
	return createReadFile(getAbsolutePath(filename).c_str());
}
Пример #15
0
ClangTool::ClangTool(const CompilationDatabase &Compilations,
                     ArrayRef<std::string> SourcePaths)
    : Files((FileSystemOptions())),
      ArgsAdjuster(new ClangSyntaxOnlyAdjuster()) {
  llvm::SmallString<1024> BaseDirectory;
  if (const char *PWD = ::getenv("PWD"))
    BaseDirectory = PWD;
  else
    llvm::sys::fs::current_path(BaseDirectory);
  for (unsigned I = 0, E = SourcePaths.size(); I != E; ++I) {
    llvm::SmallString<1024> File(getAbsolutePath(
        SourcePaths[I], BaseDirectory));

    std::vector<CompileCommand> CompileCommandsForFile =
      Compilations.getCompileCommands(File.str());
    if (!CompileCommandsForFile.empty()) {
      for (int I = 0, E = CompileCommandsForFile.size(); I != E; ++I) {
        CompileCommands.push_back(std::make_pair(File.str(),
                                  CompileCommandsForFile[I]));
      }
    } else {
      // FIXME: There are two use cases here: doing a fuzzy
      // "find . -name '*.cc' |xargs tool" match, where as a user I don't care
      // about the .cc files that were not found, and the use case where I
      // specify all files I want to run over explicitly, where this should
      // be an error. We'll want to add an option for this.
      llvm::outs() << "Skipping " << File << ". Command line not found.\n";
    }
  }
}
Пример #16
0
int HarnessTestExecutor :: validateParameters (void)
{
	try
	{ 
		_ie.tcfile = getAbsolutePath (_ie.tcfile, false);
		if (_ie.tcfile.empty ())
			throw ConfigError (FILE_LINE_FUNCTION, ERR_CONFIG_TESTCASEFILENAME_EMPTY);
		if (!bfs::is_regular (_ie.tcfile))
		{
			stringstream ss;
			ss << "Test case file " << _ie.tcfile << " either does not exist or is not a regular file.";
			throw SystemError (FILE_LINE_FUNCTION, ss.str());
		}

		if (_ie.debugLevel < MIN_DEBUG_LEVEL || _ie.debugLevel > MAX_DEBUG_LEVEL)
		{
			stringstream ss;
			ss << "Invalid value specified for option --debug. Valid range is [" << MIN_DEBUG_LEVEL << "-" << MAX_DEBUG_LEVEL << "]";
			throw ConfigError (FILE_LINE_FUNCTION, ss.str());
		}
	}

	catch (harnessexceptions :: ConfigError &e)
	{
		PRINT_ERROR (e.what ());
		return FAILURE;
	}

	return SUCCESS;
}
Пример #17
0
int hdfsCreateDirectory(hdfsFS fs, const char* path)
{
    char *url = NULL, *absPath = NULL;
    struct Response *resp = NULL;
    int ret = 0;

    if (fs == NULL || path == NULL) {
        ret = EINVAL;
        goto done;
    }
    ret = getAbsolutePath(fs, path, &absPath);
    if (ret) {
        goto done;
    }
    ret = createUrlForMKDIR(fs->nn, fs->port, absPath, fs->userName, &url);
    if (ret) {
        goto done;
    }
    ret = launchMKDIR(url, &resp);
    if (ret) {
        goto done;
    }
    ret = parseMKDIR(resp->body->content);
done:
    freeResponse(resp);
    free(url);
    free(absPath);
    if (ret) {
        errno = ret;
        return -1;
    }
    return 0;
}
/*
 * Locations where applications can place persistent files it owns.
 * E.g., /storage/org.app/Music
 */
static QString getExternalFilesDir(const char *directoryField = 0)
{
    QString &path = (*androidDirCache)[QString(QLatin1String("APPNAME_%1")).arg(QLatin1String(directoryField))];
    if (!path.isEmpty())
        return path;

    QJNIObjectPrivate activity = QtAndroidPrivate::activity();
    if (!activity.isValid())
        return QString();

    QJNIObjectPrivate appCtx = applicationContext();
    if (!appCtx.isValid())
        return QString();

    QJNIObjectPrivate dirField = QJNIObjectPrivate::fromString(QLatin1String(""));
    if (directoryField) {
        dirField = QJNIObjectPrivate::getStaticObjectField("android/os/Environment",
                   directoryField,
                   "Ljava/lang/String;");
        if (!dirField.isValid())
            return QString();
    }

    QJNIObjectPrivate file = appCtx.callObjectMethod("getExternalFilesDir",
                             "(Ljava/lang/String;)Ljava/io/File;",
                             dirField.object());

    if (!file.isValid())
        return QString();

    return (path = getAbsolutePath(file));
}
Пример #19
0
int loadWriteData(char *relpath, WriteOperation *writeop, dyndata_t *dyndata) {
    static char storedpath[PATH_MAX];
    char fpath[PATH_MAX];
    static int fd = -1;

    // a mean for closing files
    if (relpath == NULL && fd != -1) {
        if (close(fd) == -1)
            errnoMsg(LOG_WARNING, "Could not close file %s", relpath);
        return 0;
    }

    // if we are loading data the first time from this file, open it
    // last file might remain open
    if (strcmp(relpath, storedpath) != 0) {
        (void) strcpy(storedpath, relpath);

        if (fd != -1) {
            if (close(fd) == -1)
                errnoMsg(LOG_WARNING, "Could not close file %s", relpath);
        }

        getAbsolutePath(fpath, config.snapshot, relpath);
        fd = open(fpath, O_RDONLY);
        if (fd == -1) {
            errnoMsg(LOG_ERR, "Could not open source file %s", relpath);
            return -1;
        }
    }

    // realloc, if necessary (i.e. only if one operation is larger than buffer)
    // other buffer overflow cases are being taken care of in transferFile()
    if (writeop->size > dyndata->size) {
        int nsize = dyndata->size + writeop->size;

        dyndata->buf = realloc(dyndata->buf, nsize);
        if (dyndata->buf == NULL) {
            errMsg(LOG_ERR, "Could not allocate memory for write data.");
            return -1;
        }
        dyndata->size = nsize;
    }

    if (pread(fd, dyndata->buf + dyndata->offset, writeop->size,
            writeop->offset) != writeop->size) {
        errnoMsg(LOG_ERR, "Could not read data from file %s "
                "offset: %lld size: %lld",
                relpath, writeop->offset, writeop->size);
        return -1;
    }

    ProtobufCBinaryData data = {writeop->size, dyndata->buf + dyndata->offset};
    writeop->has_data = 1;
    writeop->data = data;

    dyndata->offset += writeop->size;

    return 0;
}
Пример #20
0
int ClangTool::run(ToolAction *Action) {
  // Exists solely for the purpose of lookup of the resource path.
  // This just needs to be some symbol in the binary.
  static int StaticSymbol;
  // The driver detects the builtin header path based on the path of the
  // executable.
  // FIXME: On linux, GetMainExecutable is independent of the value of the
  // first argument, thus allowing ClangTool and runToolOnCode to just
  // pass in made-up names here. Make sure this works on other platforms.
  std::string MainExecutable =
      llvm::sys::fs::getMainExecutable("clang_tool", &StaticSymbol);

  bool ProcessingFailed = false;
  for (const auto &SourcePath : SourcePaths) {
    std::string File(getAbsolutePath(SourcePath));

    std::vector<CompileCommand> CompileCommandsForFile =
        Compilations.getCompileCommands(File);
    if (CompileCommandsForFile.empty()) {
      // FIXME: There are two use cases here: doing a fuzzy
      // "find . -name '*.cc' |xargs tool" match, where as a user I don't care
      // about the .cc files that were not found, and the use case where I
      // specify all files I want to run over explicitly, where this should
      // be an error. We'll want to add an option for this.
      llvm::errs() << "Skipping " << File << ". Compile command not found.\n";
      continue;
    }
    for (CompileCommand &CompileCommand : CompileCommandsForFile) {
      // FIXME: chdir is thread hostile; on the other hand, creating the same
      // behavior as chdir is complex: chdir resolves the path once, thus
      // guaranteeing that all subsequent relative path operations work
      // on the same path the original chdir resulted in. This makes a
      // difference for example on network filesystems, where symlinks might be
      // switched during runtime of the tool. Fixing this depends on having a
      // file system abstraction that allows openat() style interactions.
      if (chdir(CompileCommand.Directory.c_str()))
        llvm::report_fatal_error("Cannot chdir into \"" +
                                 Twine(CompileCommand.Directory) + "\n!");
      std::vector<std::string> CommandLine = CompileCommand.CommandLine;
      for (const auto &Adjuster : ArgsAdjusters)
        CommandLine = Adjuster->Adjust(CommandLine);
      assert(!CommandLine.empty());
      CommandLine[0] = MainExecutable;
      // FIXME: We need a callback mechanism for the tool writer to output a
      // customized message for each file.
      DEBUG({ llvm::dbgs() << "Processing: " << File << ".\n"; });
      ToolInvocation Invocation(std::move(CommandLine), Action, Files.get());
      Invocation.setDiagnosticConsumer(DiagConsumer);
      for (const auto &MappedFile : MappedFileContents) {
        Invocation.mapVirtualFile(MappedFile.first, MappedFile.second);
      }
      if (!Invocation.run()) {
        // FIXME: Diagnostics should be used instead.
        llvm::errs() << "Error while processing " << File << ".\n";
        ProcessingFailed = true;
      }
    }
  }
Пример #21
0
void ofPackageManager::addPackageToAddonsMakeFile(ofPackage package)
{
	ofFile addonConfigFile(getAbsolutePath("addons.make"), ofFile::ReadOnly);
	if (!addonConfigFile.exists())
	{
		addonConfigFile.create();
	}
	auto stringToAdd = package._path + " #" + package._url + "@" + package._checkout;
	ofBuffer fileBuffer = addonConfigFile.readToBuffer();
	std::string content;
	auto foundPackage = false;
	for (auto line : fileBuffer.getLines())
	{
		auto words = ofSplitString(ofTrim(line), "#");
		// if path addon already listed in addon.make
		// then update it
		// else append a new line
		if (ofTrim(words[0]) == package._path)
		{
			foundPackage = true;
			content += stringToAdd;
			content += "\n";
		}
		else
		{
			content += line + "\n";
		}
		// ofLogNotice() << content;
	}
	if (!foundPackage)
	{
		content += stringToAdd;
	}
	fileBuffer.set(content.c_str(), content.size());
	addonConfigFile.close();
	ofFile newAddonsMakeFile(getAbsolutePath("addons.make"), ofFile::ReadWrite);
	if (newAddonsMakeFile.writeFromBuffer(fileBuffer))
	{
		ofLogNotice("ofPackageManager") << "successfully updated addons.make";
	}
	else
	{
		ofLogError("ofPackageManager") << "Could not update addons.make";
	}
}
Пример #22
0
static rmt_conf *
conf_open(char *filename)
{
    int ret;
    rmt_conf *cf = NULL;
    FILE *fh = NULL;
    sds path = NULL;

    if (filename == NULL) {
        log_error("ERROR: configuration file name is NULL.");
        return NULL;
    }

    path = getAbsolutePath(filename);
    if (path == NULL) {
        log_error("ERROR: configuration file name '%s' is error.", filename);
        goto error;
    }

    fh = fopen(path, "r");
    if (fh == NULL) {
        log_error("ERROR: failed to open configuration '%s': %s", path,
                  strerror(errno));
        goto error;
    }

    cf = rmt_alloc(sizeof(*cf));
    if (cf == NULL) {
        goto error;
    }

    ret = conf_init(cf);
    if(ret != RMT_OK){
        goto error;
    }

    cf->fname = path;
    cf->fh = fh;

    return cf;

error:

    if(fh != NULL) {
        fclose(fh);
    }

    if (cf != NULL) {
        conf_destroy(cf);
    }

    if (path != NULL) {
        sdsfree(path);
    }
    
    return NULL;
}
Пример #23
0
void FileSystemDisk::getFileList(const char* path, Vector<DynamicString>& files)
{
	RIO_ASSERT_NOT_NULL(path);

	TempAllocator256 ta;
	DynamicString absolutePath(ta);
	getAbsolutePath(path, absolutePath);

	OsFn::getFileList(absolutePath.getCStr(), files);
}
Пример #24
0
void FileSystemDisk::deleteFile(const char* path)
{
	RIO_ASSERT_NOT_NULL(path);

	TempAllocator256 ta;
	DynamicString absolutePath(ta);
	getAbsolutePath(path, absolutePath);

	OsFn::deleteFile(absolutePath.getCStr());
}
Пример #25
0
bool FileSystemDisk::getIsDirectory(const char* path)
{
	RIO_ASSERT_NOT_NULL(path);

	TempAllocator256 ta;
	DynamicString absolutePath(ta);
	getAbsolutePath(path, absolutePath);

	return OsFn::getIsDirectory(absolutePath.getCStr());
}
Пример #26
0
uint64_t FileSystemDisk::getLastModifiedTime(const char* path)
{
	RIO_ASSERT_NOT_NULL(path);

	TempAllocator256 ta;
	DynamicString absolutePath(ta);
	getAbsolutePath(path, absolutePath);

	return OsFn::getLastModifiedTime(absolutePath.getCStr());
}
Пример #27
0
int handleGenericOperation(int *fd, const char *relpath,
        GenericOperation *genop) {

    int ret;
    char fpath[PATH_MAX];

    // optimistic approach: we are writing the changes right in root directory
    // in case of a failure, we revert back to a snapshot
    getAbsolutePath(fpath, config.rootdir, relpath);
    //printOp(relpath, fpath, genop);

    switch (genop->type) {
        case GENERIC_OPERATION__TYPE__CREATE:
            ret = handleCreate(fpath, fd, genop->create_op);
            break;
        case GENERIC_OPERATION__TYPE__MKNOD:
            ret = handleMknod(fpath, genop->mknod_op);
            break;
        case GENERIC_OPERATION__TYPE__MKDIR:
            ret = handleMkdir(fpath, genop->mkdir_op);
            break;
        case GENERIC_OPERATION__TYPE__SYMLINK:
            ret = handleSymlink(fpath, genop->symlink_op);
            break;
        case GENERIC_OPERATION__TYPE__LINK:
            ret = handleLink(fpath, genop->link_op);
            break;
        case GENERIC_OPERATION__TYPE__WRITE:
            ret = handleWrite(fpath, fd, genop->write_op);
            break;
        case GENERIC_OPERATION__TYPE__UNLINK:
            ret = handleUnlink(fpath, fd, genop->unlink_op);
            break;
        case GENERIC_OPERATION__TYPE__RMDIR:
            ret = handleRmdir(fpath, genop->rmdir_op);
            break;
        case GENERIC_OPERATION__TYPE__TRUNCATE:
            ret = handleTruncate(fpath, genop->truncate_op);
            break;
        case GENERIC_OPERATION__TYPE__CHMOD:
            ret = handleChmod(fpath, genop->chmod_op);
            break;
        case GENERIC_OPERATION__TYPE__CHOWN:
            ret = handleChown(fpath, genop->chown_op);
            break;
        case GENERIC_OPERATION__TYPE__RENAME:
            ret = handleRename(fpath, genop->rename_op);
            break;
        case GENERIC_OPERATION__TYPE__SETXATTR:
        case GENERIC_OPERATION__TYPE__REMOVEXATTR:
            break;
    }

    return ret;
}
Пример #28
0
PUBLIC int vxchdir(char *dirname)
{
    char  *path;
    int     rc;

    path = getAbsolutePath(dirname);
    #undef chdir
    rc = chdir(path);
    wfree(path);
    return rc;
}
Пример #29
0
File* FileSystemDisk::open(const char* path, FileOpenMode::Enum mode)
{
	RIO_ASSERT_NOT_NULL(path);

	TempAllocator256 ta;
	DynamicString absolutePath(ta);
	getAbsolutePath(path, absolutePath);

	FileDisk* file = RIO_NEW(*allocator, FileDisk)();
	file->open(absolutePath.getCStr(), mode);
	return file;
}
Пример #30
0
int matchInodefiles(void) {
    fileop_t *f;
    fileop_t *finode;
    char fpath[PATH_MAX];
    struct stat st;
    int64_t inode;

    // first try to match inodefiles to files
    for (f = files; f != NULL; f = (fileop_t*) (f->hh.next)) {
        // get ino of the file
        getAbsolutePath(fpath, config.snapshot, f->relpath);

        if (stat(fpath, &st) != -1) {
            inode = st.st_ino;
        } else {
            // this should not happen: we can't open the file
            errMsg(LOG_WARNING, "Could not stat file %s ", fpath);
        }

        // if this ino is in inodefiles, merge the operations in f and
        // remove the element from inodefiles
        // TODO: what about order?
        HASH_FIND_INT(inodefiles, &inode, finode);
        if (finode != NULL) {
            if (mergeOperations(f, finode) != 0)
                return -1;

            free(finode->operations);
            HASH_DEL(inodefiles, finode);
            free(finode);
        }

        // if there are no entries in inodefiles left, we are done
        if (HASH_COUNT(inodefiles) == 0) // HASH_COUNT is cheap
            return 0;
    }

    // the rest must be matched by file tree walk (nftw)
    int flags = 0;
    flags |= FTW_MOUNT; // stay in the file system
    flags |= FTW_PHYS; // do not dereference symlinks

    if (nftw(config.snapshot, matchInode, 10, flags) == -1) {
        errMsg(LOG_WARNING, "Could not stat file %s ", fpath);
    }

    // if there are still some entries left in inodefiles, we have a problem
    if (HASH_COUNT(inodefiles) == 0)
        return 0;
    else
        return -1;
}