I have a custom SwiftLint action to flag up print() statements:
custom_rules:
disable_print:
included: ".*\\.swift"
name: "print usage"
regex: "((\\bprint)|(Swift\\.print))\\s*\\("
message: "Don't use print"
severity: error
It works but it also flags whenever I have a print() statement specified in a documentation comment like this:
/// some comment mentioning print("hello") <- Error here
func myFunc() {}
How can I alter the regex so it ignores the print statement whenever it's in a documentation comment?
It seems that a custom rule can specify what type of code will match. The property is called match_kinds, example from Swiftlint Readme:
match_kinds: # SyntaxKinds to match. optional.
- comment
- identifier
Specifying identifier should be enough for your use case.
Related
I have a nim proc that dedents a multiline string based on the whitespace
of the first indented line:
import strutils
proc dedent(s: string): string
{.noSideEffect.} =
var prefix = ""
for line in s.splitLines(keepEol=true):
if prefix == "" and line.len > 0:
for j in 0..<line.len:
if line[j] != ' ':
prefix = line[0..j-1]
break
if line.startsWith(prefix):
result.add(line[prefix.len .. high(line)])
else:
result.add(line)
when isMainModule:
echo dedent """
cat:
- meow
- purr
dog:
- bark
- drool
"""
it nicely outputs:
cat:
- meow
- purr
dog:
- bark
- drool
but inspecting the intermediate C code, I see:
STRING_LITERAL(TM_9amIjLnWbK7OR9aPA8dicbaQ_14, " cat:\012 - meow\012 - purr\012 \012 "
" dog:\012 - bark\012 - drool\012 ", 112);
so the dedenting is done at run-time. I can add the compileTime pragma to the proc:
proc dedent(s: string): string
{.noSideEffect,compileTime.} =
and then the C output changes to:
STRING_LITERAL(TM_9amIjLnWbK7OR9aPA8dicbaQ_3, "cat:\012 - meow\012 - purr\012\012dog:\012 - bark\012 - drool\012", 48);
Which is exactly what I want, multi-line strings that are indented to their surrounding on every line, but don't have that extra indentation in the executable.
But adding that pragma, I can no longer access dedent at run-time, e.g. when adding:
import os
if paramCount() > 0:
for i in 1..paramCount():
echo dedent paramStr(i)
to isMainModule, you get the error:
Error: request to generate code for .compileTime proc: dedent
I looked at the source for splitLines in strutils.nim to see if there was some other pragma that I could apply, but I did not find anything that would work.
I now about the static statement, but would prefer that the compiler optimises this at compile time without me having to sprinkle this in.
How can I get this to work both compile-time as well as run-time without reverting to the use of static?
Do I need to compile the proc from a seperate .nim module? Or is there a compiler option, pragma, something else, that I am missing?
You need to pass the --implicitStatic:on flag to the Nim compiler to enable implicit compile time evaluation of procedures.
These procedures cannot have the compileTime pragma.
To force the evaluate of any expression at compile-time, you can use static in the following way:
when isMainModule:
echo static(dedent"""
cat:
- meow
- purr
dog:
- bark
- drool
""")
All expressions assigned to constants are also evaluated at compile-time, so this is another way to achieve the same.
I have a Jenkins pipeline stage that I want to skip if there isn't a magic string in the commit message of the form Release: (major|minor|patch) (case and some whitespace insensitive) not on the first line. I'm trying to use the when directive and changelog condition, but it doesn't seem to like my regex, either because it's malformed or literally interpreting the flags .../im or escaped whitespace \s. I don't quite know how to debug it efficiently...
stage('Publish') {
when {
changelog '/.*^release:\\s*(major|minor|patch)\\s*$/im'
}
# ...
}
When it was a "bare" regex like changelog /.*^... it had a syntax error.
Is there a way to get the regex to work, or would another solution like
when {
expression {
???? ==~ /.*^release:\\s*(major|minor|patch)\\s*$/im
}
be better? Not sure what can be dropped into ????.
In Groovy/Java regex flags should come at the beginning and be wrapped in parentheses like this /(?im).*^release:\s*(major|minor|patch)\s*$/.
Also you can get commit change sets from currentBuild.changeSets. For git it returns a set of GitChangeSet.
The following should work
when {
expression {
currentBuild.changeSets.any { it.comment =~ /(?im).*^release:\s*(major|minor|patch)\s*$/ }
}
}
I'm trying to understand more about settings macros for compilation.
The Erlang compile documentation shows that a macro can be defined:
{d,Macro} {d,Macro,Value}
Defines a macro Macro to have the value Value.
Macro is of type atom, and Value can be any term.
The default Value is true.
I'm trying to set a macro using a directive:
-module(my_mod).
-compile([debug_info, {d, debug_level, 1}]).
...
How would I use this macro in my code? For example I have tried this:
my_func() ->
if
debug_level == 1 -> io:format("Warning ...");
true -> io:format("Error ...")
end.
But 'Error ...' is always output.
Where am I going wrong?
You can set a macro in your code using -define:
-define(debug_level, 1).
If you want to be able to override it from the compilation command line, you can wrap it with -ifndef:
-ifndef(debug_level).
-define(debug_level, 1).
-endif.
This way, if you compile with
erlc -Ddebug_level=2 file.erl
for example, then the macro will have the value 2 instead of the default value 1.
To access the value of a macro, you prepend it with a ?:
my_func() ->
if
?debug_level == 1 -> io:format("Warning ...");
true -> io:format("Error ...")
end.
Note that since ?debug_level is a constant, you'll get compiler warnings from the if expression about clauses that can never match.
In django, we can do this:
views.py :
def A(request):
context = {test : 'test'}
return render_to_response('index.html', context , context_instance = RequestContext(request))
def B(request):
context = {}
return render_to_response('index.html', context , context_instance = RequestContext(request))
index.html:
{% if test %}
{{ test }}
{% endif %}
And have our template render without error, even if i use method B, where variable 'test' does not exist, but I still can put it in the template.
I want to do the same with pylons + mako, in controller :
foo.py
def A(self):
c.test = 'test'
return render('index.html')
def B(self):
return render('index.html')
index.html :
% if c.test:
${'c.test'}
% endif
In Django, I can do that, but in Pylons, I get an error, is there anyway to check wheter 'c.test' exists or not?
the error : AttributeError: 'ContextObj' object has no attribute 'test'
I had a similar issue where I had multiple views using the same template and needed to test if a variable was set. I looked at the docs chris referenced and found another way to solve this problem regardless of how mako.strict_undefined is set. Essentially you call the get() method on the context object. In your example you could do the following:
% if context.get('test', UNDEFINED) is not UNDEFINED:
${test}
% endif
or
${context.get('test', '')}
That will print the same as ${test} if it exists, and print an empty string if it doesn't.
Unfortunately you can't seem to use an in operator on context which would be the most intuitive.
From the mako Docs on Context Variables:
% if someval is UNDEFINED:
someval is: no value
% else:
someval is: ${someval}
% endif
The docs describe this as referencing variable names not in the current context. Mako will set these variables to the value UNDEFINED.
I check for variables like so:
% if not someval is UNDEFINED:
(safe to use someval)
However, if pylons/pyramid has strict_undefined=True setting, attempts to use the undefined variable results in a NameError being raised. They give a brief philisophical justification for doing it this way, instead of simply replacing un-set variables with empty strings which seems consistent with Python philosophy. Took me a while to find this, but reading that entire section on the Mako Runtime will clear up how Mako recieves, sets, and uses context variables.
Edit:
For completions sake, the documents explain the strict_undefined setting here. You can change this variable by setting it in one of your .ini files:
[app:main]
...
mako.strict_undefined = false
a bit late, so whenever you use a variable on your template that doesn't exist on your controller, pylons will raise an error, to disable the error, just put this in your environment.py :
config['pylons.strict_tmpl_context'] = False
I am new to jUnit and Selenium. Currently, we are doing a POC in our project for evaluating the tools' suitability.
One of the key requirements for us would be use friendly messages in case of assertion failures and verify Failures. The objective is to have those analyzed by manual testers by keeping those user intuitive.
I am trying out SLF4J for logging INFO messages for user friendly messages.
The challenge I am facing is that - when assertions fail, how to pass a custom message instead of jUnit default message?
For example, I want to get rid of the following default assertion failure message
expected "Health A-Z" to match glob "Health A-ZZ" (had transformed the glob into regexp "Health A-ZZ"
and frame it as
The title of the Menu Item doesn't match the expected value "Health A-ZZ". The actual value seen is "Health A-Z"
Question1 - Is there a way I override the default message with what I want?
Question2 - Can I pass variable parameters to the message and make it a dynamic message?
Sample Code:
try {
assertEquals("Health A-ZZ", selenium.getText("//div[#id='topnav']/ul/li[2]/a"));
logger.info("SUCCESS: Menu Item {} title verification Passed. EXPECTED : A-Z and Actual: {}",mainCounter, selenium.getText("//div[#id='topnav']/ul/li[2]/a"));
}
catch (AssertionError e) {
logger.error("FAILURE: Menu Item {} title verification Failed. EXPECTED : A-ZZ and Actual: {}",mainCounter, selenium.getText("//div[#id='topnav']/ul/li[2]/a"));
}
I get the assertFailure message printed out twice.. One with the error message in the catch block above and the other, the default junit assertfailre message like the one I mentioned above I wanted to get rid of.
Thanks in Advance.
Regards,
Prakash
You can use the Junit assert function.
assertEquals(message, expected, actual)
This will print the message that has been given in the message String in case of failure.
You can also pass String variable to the "message".