Compile time check if file at path exists? like include_str!(..) - rust

I like how include_str!(..) works. Is there a macro that simply checks if the file exists instead of loading the contents of the file?
Use case? I want to make sure that all the file paths that are valid before I release it, to prevent runtime error.
So the file path has to be checked even if the macro isn't called during runtime.
OR should I be using tests here?

This will do for now.
#[macro_export]
macro_rules! find_file{
($arg1:literal) => {
{
//opportunity for improvement
let _ = include_bytes!($arg1);
let r = $arg1;
r
}
};
}
#PitaJ thanks

Related

gradle get relative resource path

When I iterate over source repository I do like this
def resourceDir = proj.sourceSets.main.output.resourcesDir
resourceDir.eachFileRecurse(groovy.io.FileType.FILES) { // only files will be recognized
file ->
def path = FilenameUtils.separatorsToUnix(file.toString())
if (FilenameUtils.getExtension(file.toString()) in supportedResourceExt) {
proj.logger.lifecycle("Reading file {}.", file)
//.....
}
}
In log it writes this
Reading file D:\PROJECT_FOLDER\project\subproject\subsubproject\build\resources\main\com\package\something\file.txt
How to get only the part starting with com\package\something\file.txt without explicitly reading it like file.substring(file.indexOf)?
Maybe it's posible to relativize it with project path somehow?
It seems that:
proj.logger.lifecycle("Reading file {}.", file.absolutePath - resourceDir.absolutePath)
should work. Can't check it right now.

Flatten first directory of a FileTree in Gradle

I'm writing a task to extract a tarball into a directory. I don't control this tarball's contents.
The tarball contains a single directory which contains all the files I actually care about. I want to pull everything out of that directory and copy that into my destination.
Example:
/root/subdir
/root/subdir/file1
/root/file2
Desired:
/subdir
/subdir/file1
/file2
Here's what I tried so far, but this seems like a really goofy way of doing it:
copy {
eachFile {
def segments = it.getRelativePath().getSegments() as List
it.setPath(segments.tail().join("/"))
return it
}
from tarTree(resources.gzip('mytarfile.tar.gz'))
into destinationDir
}
For each file, I get the elements of its path, remove the first, join that with /, then set that as the file's path. And this works...sort of. The problem is that this creates the following structure as a result:
/root/subdir
/root/subdir/file1
/root/file2
/subdir
/subdir/file1
/file2
I'm fine with just removing the root directory myself as a final action of the task, but I feel like there should be a much simpler way of doing this.
AFAIK, the only way is to unpack the zip, tar, tgz file :(
There is an open issue here
Please go vote for it!
Until then, the solution isn't very pretty, but not that hard either. In the example below, I am assuming that you want to remove the 'apache-tomcat-XYZ' root-level directory from a 'tomcat' configuration that only includes the apache-tomcat zip file.
def unpackDir = "$buildDir/tmp/apache.tomcat.unpack"
task unpack(type: Copy) {
from configurations.tomcat.collect {
zipTree(it).matching {
// these would be global items I might want to exclude
exclude '**/EMPTY.txt'
exclude '**/examples/**', '**/work/**'
}
}
into unpackDir
}
def mainFiles = copySpec {
from {
// use of a closure here defers evaluation until execution time
// It might not be clear, but this next line "moves down"
// one directory and makes everything work
"${unpackDir}/apache-tomcat-7.0.59"
}
// these excludes are only made up for an example
// you would only use/need these here if you were going to have
// multiple such copySpec's. Otherwise, define everything in the
// global unpack above.
exclude '**/webapps/**'
exclude '**/lib/**'
}
task createBetterPackage(type: Zip) {
baseName 'apache-tomcat'
with mainFiles
}
createBetterPackage.dependsOn(unpack)
Using groovy's syntax, we can use a regex to eliminate the first path segment:
task myCopyTask(type: Copy) {
eachFile {
path -= ~/^.+?\//
}
from tarTree(resources.gzip('mytarfile.tar.gz'))
into destinationDir
includeEmptyDirs = false // ignore empty directories
}

puppet, getting the $name when instantiating a resource type with an array

using puppet, i need to create three files, with this content:
/tmp/f1.txt: hello /tmp/f1.txt
/tmp/f2.txt: hello /tmp/f2.txt
/tmp/f3.txt: hello /tmp/f3.txt
i try as follows:
$path="/tmp/"
$my_files = ["$path/f1.txt", "$path/f2.txt", "$path/f3.txt"]
file { $my_files:
ensure => file,
content => "hello $name\n",
}
however this does not work because $name is undefined.
is there a variable that gets instantiated for each 'iteration' and that i can use?
ps: i am aware that i could create a new resource type as follows:
define file_with_content {
file { $name:
ensure => file,
content => "hello $name\n",
}
}
$path="/tmp/"
$my_files = ["$path/f1.txt", "$path/f2.txt", "$path/f3.txt"]
file_with_content { $my_files: }
but this requires creating a new resource type,
and I cannot do this in my context (which is not explained here).
the question is, how to modify the first code to make it work, without defining a new resource type, nor executing shell code?
You only can access the namevar for defined types. For Puppet's resources, the results are unpredictable - for example, $name for File will give you main, or the current stage. Additionally, you cannot pass/utilize extra parameters to Puppet's resources as they have their own set of parameters already.
The standard solution has been to wrap the File declaration in a defined type like here, like your first. Perhaps you can explain why that cannot be used, so some other solution could be devised?

How to read a custom path of a file in c++?

My file is located in C:\\Input\\pStep.p21 . i want to open that file in my cpp program. How can i do it? I am using char* inputPath="C:\\Input\\pStep.p21"; but its not finding my file in program. How to get current working directory in VC++?. Its working if try to save p21 file but failing if i read it.
my code in CAA:
#include<CATSDM_Services>
#include<SdaiModel.h>
#include<CATIUniCodeString>
---
---
main()
{
CATIUniCodeString inputPath("C:\\Input\\pStep.p21");
HRESULT hr=S_OK;
SdaiModel edxModel=Null;
//this method reads express schema name, input p21 file and sdaimodel
hr=CreateModelFromFile(inputPath,"parts",edxModel);
if(FAILED(hr))
{
cout<<"Model created succesfully";
}
else
{
cout<<"Failed";
}
}
Sorry for not seeing the question earlier.
From what I am seeing in your code, the test is wrong. The FAILED() macro denotes incorrect execution. Thus from you code, if you see "Failed" on the console, it actually means the execution of the method ran OK.
Change your code to something like:
if ( SUCCEEDED(hr) )
{
cout<<"Model created succesfully";
}
else
{
cout<<"Failed";
}

Check a file already exists in Save As Dialog box - c++, opencascade

I want to create a .stl file for a particular shape where each face of that shape has a different patch name like face1,face 2 etc. I have done this by overriding the StlAPI_Writer and RWStl classes in opencascade. I have used file.Append method instead of file.Build method to do so.
But I have a problem when I save the .stl file in an already existing file, it appends data to the existing one which is incorrect. I want to delete the existing data in the file and append new data face by face for a given shape.
Please help me on this.
You can use this simple function:
#include <sys/stat.h>
#include <string>
using namespace std;
bool FileExists(string strFilename) {
struct stat stFileInfo;
bool blnReturn;
int intStat;
// Attempt to get the file attributes
intStat = stat(strFilename.c_str(),&stFileInfo);
if(intStat == 0) {
// We were able to get the file attributes
// so the file obviously exists.
blnReturn = true;
} else {
// We were not able to get the file attributes.
// This may mean that we don't have permission to
// access the folder which contains this file. If you
// need to do that level of checking, lookup the
// return values of stat which will give you
// more details on why stat failed.
blnReturn = false;
}
return(blnReturn);
}
I assume you use the SaveFileDialogue class. In this case you can handle the return result of the dialogue like this:
if ( saveFileDialog.ShowDialog() == ::DialogResult::OK ) {
if ( FileExist(saveFileDialog.FileName) ) {
// erase the file
}
// write the code using the Append function
}
This should work, however a easier variant must be accessible if you use something else than Append (something like Write or maybe even Append but with a parameter that specifies to rewrite the file)
HTH, JP

Resources