Rubocop: how can I exclude a filename pattern from a metric? - rubocop

I want to disable line length checking globally for filenames matching *_spec.rb (Serverspec files) in Rubocop.
I tried adding Exclude to config/default.yml in the following way, but it did not work (no error, offenses detected):
Metrics/LineLength:
Max: 80
AllowHeredoc: true
AllowURI: true
URISchemes:
- http
- https
Exclude:
- '*_spec.rb'
If it is possible, where/how should this be configured?

You can match files based on a regular expression by using the !ruby/regexp declaration:
Metrics/LineLength:
Max: 80
AllowHeredoc: true
AllowURI: true
URISchemes:
- http
- https
Exclude:
- !ruby/regexp /_spec\.rb$/
RuboCop recently added a new manual, and you can read about including and excluding files here.

Related

Inject Key Storage Password into Option's ValuesUrl

I'm trying to request a raw file from a Gitlab repository as a values JSON file for my job option. The only way so far that I managed to do it is by writing my secret token as plain text in the request URL:
https://mycompanygitlab.com/api/v4/projects/XXXX/repository/files/path%2Fto%2Fmy%2Ffile.json/raw?ref=main&private_token=MyV3ry53cr3Tt0k3n
I've tried using option cascading; I created a Secure password Input Option called gitlab_token which points to a Key Storage Password and tried every possible notation (with or without .value, quoted or unquoted option) in the valuesUrl field of the second option, instead of the plain token, but I keep receiving this error message pointing an invalid char at the position of the dollar sign:
I've redacted sensitive info and edited the error print accordingly
I reproduced your issue. It works using a text option, you can use the value in this way: ${option.mytoken.value}.
- defaultTab: nodes
description: ''
executionEnabled: true
id: e4f114d5-b3af-44a5-936f-81d984797481
loglevel: INFO
name: ResultData
nodeFilterEditable: false
options:
- name: mytoken
value: deda66698444
- name: apiendpoint
valuesUrl: https://mocki.io/v1/xxxxxxxx-xxxx-xxxx-xxxx-${option.mytoken.value}
plugins:
ExecutionLifecycle: null
scheduleEnabled: true
sequence:
commands:
- exec: echo ${option.mytoken}
- exec: echo ${option.apiendpoint}
keepgoing: false
strategy: node-first
uuid: e4f114d5-b3af-44a5-936f-81d984797481
Another workaround (if you don't want to use a plain text option) could be to pass the secure option to an inline script and manage the logic from there.
Please open a new issue here.

SaltStack - Unable to check if file exists on minion

I am trying to check if a particular file with some extension exists on a centos host using salt stack.
create:
cmd.run:
- name: touch /tmp/filex
{% set output = salt['cmd.run']("ls /tmp/filex") %}
output:
cmd.run:
- name: "echo {{ output }}"
Even if the file exists, I am getting the error as below:
ls: cannot access /tmp/filex: No such file or directory
I see that you already accepted an answer for this that talks about jinja being rendered first. which is true. but i wanted to add to that you don't have to use cmd.run to check the file. there is a state that is built in to salt for this.
file.exists will check for a file or directories existence in a stateful way.
One of the things about salt is you should be looking for ways to get away from cmd.run when you can.
create:
file.managed:
- name: /tmp/filex
check_file:
file.exists:
- name: /tmp/filex
- require:
- file: create
In SaltStack Jinja is evaluated before YAML. The file creation will (cmd.run) be executed after Jinja. So your Jinja variable is empty because the file isn’t created, yet.
See https://docs.saltproject.io/en/latest/topics/jinja/index.html
Jinja statements such as your set output line are evaluated when the sls file is rendered, before any of the states in it are executed. It's not seeing the file because the file hasn't been created yet.
Moving the check to the state definition should fix it:
output:
cmd.run:
- name: ls /tmp/filex
# if your underlying intent is to ensure something runs only
# once the file exists, you can enforce that here
- require:
- cmd: create

Rubocop not ignoring db/schema.rb file

Why is my db/schema.rb file not being ignored by rubocop?
.rubocop.yml
require: rubocop-rails
require: rubocop-performance
AllCops:
Exclude:
- 'db/**/*'
- 'config/**/*'
- 'script/**/*'
- 'bin/{rails,rake}'
- 'vendor/**/*'
- 'spec/fixtures/**/*'
- 'tmp/**/*'
- 'Gemfile.lock'
Rails:
Enabled: true
# Commonly used screens these days easily fit more than 80 characters.
Metrics/LineLength:
Max: 120
# Too short methods lead to extraction of single-use methods, which can make
# the code easier to read (by naming things), but can also clutter the class
Metrics/MethodLength:
Max: 20
Metrics/BlockLength:
ExcludedMethods: ['describe', 'context', 'FactoryBot.define']
# The guiding principle of classes is SRP, SRP can't be accurately measured by LoC
Metrics/ClassLength:
Max: 1500
# No space makes the method definition shorter and differentiates
# from a regular assignment.
Layout/SpaceAroundEqualsInParameterDefault:
EnforcedStyle: no_space
Naming/VariableNumber:
EnforcedStyle: normalcase
# Single quotes being faster is hardly measurable and only affects parse time.
# Enforcing double quotes reduces the times where you need to change them
# when introducing an interpolation. Use single quotes only if their semantics
# are needed.
Style/StringLiterals:
EnforcedStyle: double_quotes
# We do not need to support Ruby 1.9, so this is good to use.
Style/SymbolArray:
Enabled: true
# Most readable form.
Layout/AlignHash:
EnforcedHashRocketStyle: table
EnforcedColonStyle: table
# Mixing the styles looks just silly.
Style/HashSyntax:
EnforcedStyle: ruby19_no_mixed_keys
# has_key? and has_value? are far more readable than key? and value?
Style/PreferredHashMethods:
Enabled: false
# String#% is by far the least verbose and only object oriented variant.
Style/FormatString:
EnforcedStyle: percent
Style/CollectionMethods:
Enabled: true
PreferredMethods:
# inject seems more common in the community.
reduce: "inject"
# Either allow this style or don't. Marking it as safe with parenthesis
# is silly. Let's try to live without them for now.
Style/ParenthesesAroundCondition:
AllowSafeAssignment: false
Lint/AssignmentInCondition:
AllowSafeAssignment: false
# A specialized exception class will take one or more arguments and construct the message from it.
# So both variants make sense.
Style/RaiseArgs:
Enabled: false
# Indenting the chained dots beneath each other is not supported by this cop,
# see https://github.com/bbatsov/rubocop/issues/1633
Layout/MultilineOperationIndentation:
Enabled: false
# Fail is an alias of raise. Avoid aliases, it's more cognitive load for no gain.
# The argument that fail should be used to abort the program is wrong too,
# there's Kernel#abort for that.
Style/SignalException:
EnforcedStyle: only_raise
# Suppressing exceptions can be perfectly fine, and be it to avoid to
# explicitly type nil into the rescue since that's what you want to return,
# or suppressing LoadError for optional dependencies
Lint/HandleExceptions:
Enabled: false
Layout/SpaceInsideBlockBraces:
# The space here provides no real gain in readability while consuming
# horizontal space that could be used for a better parameter name.
# Also {| differentiates better from a hash than { | does.
SpaceBeforeBlockParameters: false
# No trailing space differentiates better from the block:
# foo} means hash, foo } means block.
Layout/SpaceInsideHashLiteralBraces:
EnforcedStyle: no_space
# { ... } for multi-line blocks is okay, follow Weirichs rule instead:
# https://web.archive.org/web/20140221124509/http://onestepback.org/index.cgi/Tech/Ruby/BraceVsDoEnd.rdoc
Style/BlockDelimiters:
Enabled: false
# do / end blocks should be used for side effects,
# methods that run a block for side effects and have
# a useful return value are rare, assign the return
# value to a local variable for those cases.
Style/MethodCalledOnDoEndBlock:
Enabled: true
# Enforcing the names of variables? To single letter ones? Just no.
Style/SingleLineBlockParams:
Enabled: false
# Shadowing outer local variables with block parameters is often useful
# to not reinvent a new name for the same thing, it highlights the relation
# between the outer variable and the parameter. The cases where it's actually
# confusing are rare, and usually bad for other reasons already, for example
# because the method is too long.
Lint/ShadowingOuterLocalVariable:
Enabled: false
# Check with yard instead.
Style/Documentation:
Enabled: false
# This is just silly. Calling the argument `other` in all cases makes no sense.
Naming/BinaryOperatorParameterName:
Enabled: false
# There are valid cases, for example debugging Cucumber steps,
# also they'll fail CI anyway
Lint/Debugger:
Enabled: false
# Style preference
Style/MethodDefParentheses:
Enabled: false
I know this is an old question, but in case anybody's still having a similar issue:
When specifying multiple extensions such as rubocop-rails and rubocop-performance, provide them as an array to the require: directive, e.g.:
require:
- rubocop-rails
- rubocop-performance
Also worth noting is that rubocop-rails now ignores db/schema.rb by default (since version 2.4.1).
In my case I added only
AllCops:
Excludes:
- config/unicorn.rb
- db/**
Style/Documentation:
...
and rubocop is worked
In case anyone has the same confusion.. In my case, this was not actually a Rubocop issue. Running rails db:migrate was causing schema to be recreated and the column positions adjusted.

No files included in stash exception

I am using stash command in groovy script. I am getting:
Caught: hudson.AbortException: No files included in stash
However the logs before the exception says:
Stashed 1 file(s)
[Pipeline] stash
Stashed 1 file(s)
can you please advise
I'm guessing based on your log you're doing more than one stash, perhaps you do have one that doesn't have any files, in that case you need allowEmpty: true
stash allowEmpty: true, includes: 'foo', name: 'bar'
I had this problem. I was making a mistake by specifying multiple files by name without comma separator. Correct way is:
stash includes: "a.bin,a.log", name: "<name>"
Please use "Pipeline Syntax" link to generate command and read description of fields you want to use.

Jekyll Filename Without Date

I want to build documentation site using Jekyll and GitHub Pages. The problem is Jekyll only accept a filename under _posts with exact pattern like YYYY-MM-DD-your-title-is-here.md.
How can I post a page in Jekyll without this filename pattern? Something like:
awesome-title.md
yet-another-title.md
etc.md
Thanks for your advance.
Don't use posts; posts are things with dates. Sounds like you probably want to use collections instead; you get all the power of Posts; but without the pesky date / naming requirements.
https://jekyllrb.com/docs/collections/
I use collections for almost everything that isn't a post. This is how my own site is configured to use collections for 'pages' as well as more specific sections of my site:
I guess that you are annoyed with the post url http://domaine.tld/category/2014/11/22/post.html.
You cannot bypass the filename pattern for posts, but you can use permalink (see documentation).
_posts/2014-11-22-other-post.md
---
title: "Other post"
date: 2014-11-22 09:49:00
permalink: anything-you-want
---
File will be anything-you-want/index.html.
Url will be http://domaine.tld/anything-you-want.
What I did without "abandoning" the posts (looks like using collections or pages is a better and deeper solution) is a combination of what #igneousaur says in a comment plus using the same date as prefix of file names:
Use permalink: /:title.html in _config.yml (no dates in published URLs).
Use the format 0001-01-01-name.md for all files in _posts folder (jekyll is happy about the file names and I'm happy about the sorting of the files).
Of course, we can include any "extra information" on the name, maybe some incremental id o anything that help us to organize the files, e.g.: 0001-01-01-001-name.md.
The way I solved it was by adding _plugins/no_date.rb:
class Jekyll::PostReader
# Don't use DATE_FILENAME_MATCHER so we don't need to put those stupid dates
# in the filename. Also limit to just *.markdown, so it won't process binary
# files from e.g. drags.
def read_posts(dir)
read_publishable(dir, "_posts", /.*\.markdown$/)
end
def read_drafts(dir)
read_publishable(dir, "_drafts", /.*\.markdown$/)
end
end
This overrides ("monkey patches") the standard Jekyll functions; the defaults for these are:
# Read all the files in <source>/<dir>/_drafts and create a new
# Document object with each one.
#
# dir - The String relative path of the directory to read.
#
# Returns nothing.
def read_drafts(dir)
read_publishable(dir, "_drafts", Document::DATELESS_FILENAME_MATCHER)
end
# Read all the files in <source>/<dir>/_posts and create a new Document
# object with each one.
#
# dir - The String relative path of the directory to read.
#
# Returns nothing.
def read_posts(dir)
read_publishable(dir, "_posts", Document::DATE_FILENAME_MATCHER)
end
With the referenced constants being:
DATELESS_FILENAME_MATCHER = %r!^(?:.+/)*(.*)(\.[^.]+)$!.freeze
DATE_FILENAME_MATCHER = %r!^(?>.+/)*?(\d{2,4}-\d{1,2}-\d{1,2})-([^/]*)(\.[^.]+)$!.freeze
As you can see, DATE_FILENAME_MATCHER as used in read_posts() requires a date ((\d{2,4}-\d{1,2}-\d{1,2})); I put date: 2021-07-06 in the frontmatter.
I couldn't really get collections to work, and this also solves another problem I had where storing binary files such as images in _drafts would error out as it tried to process them.
Arguably a bit ugly, but it works well. Downside is that it may break on update, although I've been patching various things for years and never really had any issues with it thus far. This is with Jekyll 4.2.0.
I wanted to use posts but not have the filenames in the date. The closest I got was naming the posts with an arbitrary 'date' like 0001-01-01cool-post.md and then use a different property to access the date.
If you use the last-modified-at plugin - https://github.com/gjtorikian/jekyll-last-modified-at - then you can use page.last_modified_at in your _layouts/post.html and whatever file you are running {% for post in site.posts %} in.
Now the dates are retrieved from the last git commit date (not author date) and the page.date is unused.
In the json schema for the config file are actually some useful information. See below code block for some examples.
I have set it to /:categories/:title. That drops the date and file extension, while preserving the categories.
I still use a proper date for the file name because you can use that date in your templates. I.e. to display the date on a post using {{ page.date }}.
{
"global-permalink": {
"description": "The global permalink format\nhttps://jekyllrb.com/docs/permalinks/#global",
"type": "string",
"default": "date",
"examples": [
"/:year",
"/:short_year",
"/:month",
"/:i_month",
"/:short_month",
"/:day",
"/:i_day",
"/:y_day",
"/:w_year",
"/:week",
"/:w_day",
"/:short_day",
"/:long_day",
"/:hour",
"/:minute",
"/:second",
"/:title",
"/:slug",
"/:categories",
"/:slugified_categories",
"date",
"pretty",
"ordinal",
"weekdate",
"none",
"/:categories/:year/:month/:day/:title:output_ext",
"/:categories/:year/:month/:day/:title/",
"/:categories/:year/:y_day/:title:output_ext",
"/:categories/:year/:week/:short_day/:title:output_ext",
"/:categories/:title:output_ext"
],
"pattern": "^((/(:(year|short_year|month|i_month|short_month|long_month|day|i_day|y_day|w_year|week|w_day|short_day|long_day|hour|minute|second|title|slug|categories|slugified_categories))+)+|date|pretty|ordinal|weekdate|none)$"
}
}