How to check a particular line using Inspec test - inspec

How do I check if the first line of the file contains a certain string using Inspec test? Currently, I am doing this.
describe file ('/path/to/file/filename')do
it { should exist }
its('content') { should match 'build/path/location' }
end
end
How can I make it better not to check the whole content but only the first line?

To check the file content (Eg.: rsyslog.conf) were content should be *.=/var/log/debug.log
Then the following Module will help you to test it.
control "rsyslog-1-2-2" do
impact 1.0
desc "Checking Inside rsyslog configuration File & checking the Application Logs Conf. has been set it up."
describe file("/etc/rsyslog.conf") do
its('content') { should match(%r{^\*.=debug\s.*?/var/log/debug.log}) }
end
end

Related

How to check which file is importing this file in Lua?

I've been constructing a packet analising system for wireshark with Lua script.
Now I'm managing three following lua files where VPS.lua and DSS.lua are importing some functions from DSS_function.lua by require module.
VPS.lua DSS.lua DSS_function.lua
Question is how to know which file, VPS.lua or DSS.lua, DSS_function.lua are imported from.
DSS_function.lua has to know this information, because each time it declares the protocol depending on the file which is importing itself.
Thank you.
You can use something along these lines to figure out where a library is required from:
local name = debug.getinfo(3).short_src
if name:find "foo.lua" then
print("Required from Foo")
elseif name:find "bar.lua" then
print("Required from Bar")
end
But the problem is that it will only work the first time because Lua caches modules after the first time they are required.
Setting that aside, what you are trying to build is an abomination and whatever reason you think you have for wanting this is just a sign of a deeper problem with your code structure.
If you use require("name_of_the_Lua_file") then the return of the required Lua file goes to...
package.loaded.name_of_the_Lua_file
The next require("name_of_the_Lua_file") looks for this name in package.loaded.name_of_the_Lua_file and if there it loads it from there.
Only if the Lua file dont return anything then package.loaded.name_of_the_Lua_file returns a: true
...and not what you expected.
Example what i mean...
package.loaded.example={test = function() print "Hi - I am a test" end}
require('example').test()
-- Output: Hi - I am a test
So, check what is allready required with a look in package.loaded.
It could look like...
if package.loaded.example ~= nil then
print("Already loaded")
return true
else
print("Not exists - Load it first")
return false
end
-- Output: Already loaded
-- true

Output text at the very end of custom Nx workspace generator

Is it possible to output/log text at the very end the workspace generator output?
I would like to notify the user of the next steps he/she should do, but my logs are kind of hidden above all the output generated by the tree updates.
export default async function (tree: Tree, schema: GeneratorOptions) {
await applicationGenerator(tree, {
// options go here
});
//format all the new files
await formatFiles(tree);
// log out next steps
logger.info('next steps');
logger.info('* Complete information in /src/environment files');
logger.info('* Adjust example routes in /src/app/app.tsx');
}
The code above results in the following output, as you can see my logs are completely at the top (and nobody would ever see them)
I was having the same problem and judging from this open issue it does not seem to be a way to do it.
What I ended up doing was wrapping the command to run the generator in a node script and then run that script instead:
import {execSync} from "child_process";
execSync('nx workspace-generator your-generator', {stdio: 'inherit'})
console.log('after')

install4j: how can i pass command line arguments to windows service

I've created a windows service using install4j and everything works but now I need to pass it command line arguments to the service. I know I can configure them at service creation time in the new service wizard but i was hoping to either pass the arguments to the register service command ie:
myservice.exe --install --arg arg1=val1 --arg arg1=val2 "My Service Name1"
or by putting them in the .vmoptions file like:
-Xmx256m
arg1=val1
arg2=val2
It seems like the only way to do this is to modify my code to pick up the service name via exe4j.launchName and then load some other file or environment variables that has the necessary configuration for that particular service. I've used other service creation tools for java in the past and they all had straightforward support for command line arguments registered by the user.
I know you asked this back in January, but did you ever figure this out?
I don't know where you're sourcing val1, val2 etc from. Are they entered by the user into fields in a form in the installation process? Assuming they are, then this is a similar problem to one I faced a while back.
My approach for this was to have a Configurable Form with the necessary fields (as Text Field objects), and obviously have variables assigned to the values of the text fields (under the 'User Input/Variable Name' category of the text field).
Later in the installation process I had a Display Progress screen with a Run Script action attached to it with some java to achieve what I wanted to do.
There are two 'gotchas' when optionally setting variables in install4j this way. Firstly, the variable HAS to be set no matter what, even if it's just to the empty string. So, if the user leaves a field blank (ie they don't want to pass that argument into the service), you'll still need to provide an empty string to the Run executable or Launch Service task (more in that in a moment) Secondly, arguments can't have spaces - every space-separated argument has to have its own line.
With that in mind, here's a Run script code snippet that might achieve what you want:
final String[] argumentNames = {"arg1", "arg2", "arg3"};
// For each argument this method creates two variables. For example for arg1 it creates
// arg1ArgumentIdentifierOptional and arg1ArgumentAssignmentOptional.
// If the value of the variable set from the previous form (in this case, arg1) is not empty, then it will
// set 'arg1ArgumentIdentifierOptional' to '--arg', and 'arg1ArgumentAssignmentOptional' to the string arg1=val1 (where val1
// was the value the user entered in the form for the variable).
// Otherwise, both arg1ArgumentIdentifierOptional and arg1ArgumentAssignmentOptional will be set to empty.
//
// This allows the installer to pass both parameters in a later Run executable task without worrying about if they're
// set or not.
for (String argumentName : argumentNames) {
String argumentValue = context.getVariable(argumentName)==null?null:context.getVariable(argumentName)+"";
boolean valueNonEmpty = (argumentValue != null && argumentValue.length() > 0);
context.setVariable(
argumentName + "ArgumentIdentifierOptional",
valueNonEmpty ? "--arg": ""
);
context.setVariable(
argumentName + "ArgumentAssignmentOptional",
valueNonEmpty ? argumentName+"="+argumentValue : ""
);
}
return true;
The final step is to launch the service or executable. I'm not too sure how services work, but with the executable, you create the task then edit the 'Arguments' field, giving it a line-separated list of values.
So in your case, it might look like this:
--install
${installer:arg1ArgumentIdentifierOptional}
${installer:arg1ArgumentAssignmentOptional}
${installer:arg2ArgumentIdentifierOptional}
${installer:arg2ArgumentAssignmentOptional}
${installer:arg3ArgumentIdentifierOptional}
${installer:arg3ArgumentAssignmentOptional}
"My Service Name1"
And that's it. If anyone else knows how to do this better feel free to improve on this method (this is for install4j 4.2.8, btw).

ICU custom transliteration

I am looking to utilize the ICU library for transliteration, but I would like to provide a custom transliteration file for a set of specific custom transliterations, to be incorporated into the ICU core at compile time for use in binary form elsewhere. I am working with the source of ICU 4.2 for compatibility reasons.
As I understand it, from the ICU Data page of their website, one way of going about this is to create the file trnslocal.mk within ICUHOME/source/data/translit/ , and within this file have the single line TRANSLIT_SOURCE_LOCAL=custom.txt.
For the custom.txt file itself, I used the following format, based on the master file root.txt:
custom{
RuleBasedTransliteratorIDs {
Kanji-Romaji {
file {
resource:process(transliterator){"custom/Kanji_Romaji.txt"}
direction{"FORWARD"}
}
}
}
TransliteratorNamePattern {
// Format for the display name of a Transliterator.
// This is the language-neutral form of this resource.
"{0,choice,0#|1#{1}|2#{1}-{2}}" // Display name
}
// Transliterator display names
// This is the English form of this resource.
"%Translit%Hex" { "%Translit%Hex" }
"%Translit%UnicodeName" { "%Translit%UnicodeName" }
"%Translit%UnicodeChar" { "%Translit%UnicodeChar" }
TransliterateLATIN{
"",
""
}
}
I then store within the directory custom the file Kanji_Romaji.txt, as found here. Because it uses > instead of the → I have seen in other files, I converted each entry appropriately, so they now look like:
丁 → Tei ;
七 → Shichi ;
When I compile the ICU project, I am presented with no errors.
When I attempt to utilize this custom transliterator within a testfile, however (a testfile that works fine with the in-built transliterators), I am met with the error error: 65569:U_INVALID_ID.
I am using the following code to construct the transliterator and output the error:
UErrorCode status = U_ZERO_ERROR;
Transliterator *K_R = Transliterator::createInstance("Kanji-Romaji", UTRANS_FORWARD, status);
if (U_FAILURE(status))
{
std::cout << "error: " << status << ":" << u_errorName(status) << std::endl;
return 0;
}
Additionally, a loop through to Transliterator::countAvailableIDs() and Transliterator::getAvailableID(i) does not list my custom transliteration. I remember reading with regard to custom converters that they must be registered within /source/data/mappings/convrtrs.txt . Is there a similar file for transliterators?
It seems that my custom transliterator is either not being built into the appropriate packages (though there are no compile errors), is improperly formatted, or somehow not being registered for use. Incidentally, I am aware of the RuleBasedTransliterator route at runtime, but I would prefer to be able to compile the custom transliterations for use in any produced binary.
Let me know if any additional clarification is necessary. I know there is at least one ICU programmer on here, who has been quite helpful in other posts I have written and seen elsewhere as well. I would appreciate any help I can find. Thank you in advance!
Transliterators are sourced from CLDR - you could add your transliterator to CLDR (the crosswire directory contains it in XML format in the cldr/ directory) and rebuild ICU data. ICU doesn't have a simple mechanism for adding transliterators as you are trying to do. What I would do is forget about trnslocal.mk or custom.txt as you don't need to add any files, and simply modify root.txt - you might file a bug if you have a suggested improvement.

How do I pass build number from Nant back to Cruise Control

I have a Nant build script which CruiseControl uses to build a solution on-demand.
However, we only recently got CruiseControl so our official build number is different from what is listed in CruiseControl.
I know CruiseControl injects some properties into build scripts so that I can access the CC build number in the script (CCNetLabel) but how do I pass a value back to CC to use as the build number on the UI screen?
Example, CC says build number 2
nAnt script increments a buildnumber.xml value every build, and the official build number is on 123.
I want the CC UI to show last successful build number: 123, not 2, so how do I pass that value back up?
A custom build labeler is required for this. Perforce is our source control provider and we derive our version number from it. The code is as follows:
/// <summary>
/// Gets the latest change list number from perforce, for ccnet to consume as a build label.
/// </summary>
[ReflectorType( "p4labeller" )]
public class PerforceLabeller : ILabeller
{
// perforce executable (optional)
[ReflectorProperty("executable", Required = false)]
public string P4Executable = "p4.exe";
// perforce port (i.e. myserver:1234)
[ReflectorProperty("port", Required = false)]
public string P4Port = String.Empty;
// perforce user
[ReflectorProperty("user", Required = false)]
public string P4User = String.Empty;
// perforce client
[ReflectorProperty("client", Required = false)]
public string P4Client = String.Empty;
// perforce view (i.e. //Dev/Code1/...)
[ReflectorProperty("view", Required = false)]
public string P4View = String.Empty;
// Returns latest change list
public string Generate( IIntegrationResult previousLabel )
{
return GetLatestChangelist();
}
// Stores latest change list into a label
public void Run( IIntegrationResult result )
{
result.Label = GetLatestChangelist();
}
// Gets the latest change list
public string GetLatestChangelist()
{
// Build the arguments to pass to p4 to get the latest changelist
string theArgs = "-p " + P4Port + " -u " + P4User + " -c " + P4Client + " changes -m 1 -s submitted " + P4View;
Log.Info( string.Format( "Getting latest change from Perforce using --> " + theArgs ) );
// Execute p4
ProcessResult theProcessResult = new ProcessExecutor().Execute( new ProcessInfo( P4Executable, theArgs ) );
// Extract the changelist # from the result
Regex theRegex = new Regex( #"\s[0-9]+\s", RegexOptions.IgnoreCase );
Match theMatch = theRegex.Match( theProcessResult.StandardOutput );
return theMatch.Value.Trim();
}
}
The method, GetLatestChangelist, is where you would probably insert your own logic to talk to your version control system. In Perforce there is the idea of the last changelist which is unique. Our build numbers, and ultimately version numbers are based off of that.
Once you build this (into an assembly dll), you'll have to hook it into ccnet. You can just drop the assembly into the server directory (next to ccnet.exe).
Next you modify your ccnet project file to utilize this labeller. We did this with the default labeller block. Something like the following:
<project>
<labeller type="p4labeller">
<client>myclient</client>
<executable>p4.exe</executable>
<port>myserver:1234</port>
<user>myuser</user>
<view>//Code1/...</view>
</labeller>
<!-- Other project configuration to go here -->
</project>
If you're just wanting the build number to show up in ccnet then you're done and don't really need to do anything else. However, you can access the label in your NAnt script if you wish by using the already provided CCNetLabel property.
Hope this helps some. Let me know if you have any questions by posting to the comments.
Did you try to use some environment variables? I believe CCNet can handle these.
I'll dig a bit on this.
Well I see a solution, quite dirty, but anyhow:
1- Add a defaultlabeller section in your CCNET project definition. It will contains the pattern of the build number you want to display.
2- Within NAnt, have a script to update your configuration file, inserting the build number you want to see.
3- Touch (in the Unix sense) the ccnet.exe.config file so as to make it re-load the projects configuration files.
et voilà.
We had this problem as well. I ended up writing a special CC labelling plugin.
If your build numbers are sequential, you can just hack the cruise control state file to give it the correct build number to start with. Your looking for a file called [projectName].state.
I changed the Label element to the correct number and the LastSuccessfulIntegrationLabel to be the new number.
However, we only recently got
CruiseControl so our official build
number is different from what is
listed in CruiseControl.
Sort of along the lines of what gbanfill said, you can tell CC what build numbers to start from, but there's no need to hack the .ser file. You can use the JMX interface to set the current build number to get it in sync with your NAnt build number.
You can also set the default label value to to your current build number, delete the .ser file and restart CC.
But maybe the easiest thing is to write the build number into a property file from NAnt and then use the property file label incrementer to read that file. (Be sure to to set setPreBuildIncrementer="true")