How to write a file using LF instead of CRLF on Windows? - node.js

We have a script that runs as the preinstall script. It uses fs.writeFile to write a config file which it generates.
writeFile(configFilePath, configFileContents, (e) => {
// ... do some error handling
}
For some reason it uses CRLF line endings on Windows and creating diffs in git although the file has not changed.
I have tried to do use
.replace(/\r\n/gm, "\n");
on configFileContents but it still uses the Windows line endings.
configFileContents gets created by:
const configFileContents = JSON.stringify({
foo: bar,
baz, foo,
// ...
}, null, 2);
Is there a way to tell Node to use the Linux ones?

You can simply do this:
.replace(/\r\n/g, "\n")
Also /\r\n/gm regexp isn't correct as you're already telling the Regexp engine to look for new line by providing the m/multiple lines option... That's why it doesn't allow the expression to work. Just use g if you really wan't to use the RegExp

I used prettier to update the file automatically after the file was created, that worked for me. So i just added prettier command in extention to the file creation npm script.
prettier \"supportedBrowsers.ts\" --write"

Related

How do you disable no-plusplus when using eslint?

When using eslint in Visual Studio Code, AirBnB style Ubuntu Linux, no-plusplus is enabled as default so using ++ for example in a for loop will error: [eslint] Unary operator '++' used. (no-plusplus)
How do you disable that setting?
You can just override it in your .eslintrc.js file as follows:
'no-plusplus': 'off'
or if you don't want to disable it completely but only for for-loops:
'no-plusplus': [2, { allowForLoopAfterthoughts: true }]
You can also write variable += 1 instead, as suggested by ESLint.
You can locate the file location you need to alter on Linux by searching for the keyword using grep, in this case to search for the file containing plusplus when in the folder eslint was installed use
grep -r plusplus
The correct file will be the eslint-config file, in this case it should be: node_modules/eslint-config-airbnb-base/rules/style.js
To disable the setting comment out the no-plusplus line, you can easily re-enable if required:
// 'no-plusplus': 'error',
Or you can go like this:
'no-plusplus': 0,
You can simply write your declared variable += 1 instead, as suggested by ESLint.
varible++ is similar as variable+=1.

Inserting a string into a file with Puppet with iteration

I'm running a .each iteration with Puppet:
$extensions_list = ["RT::Extension::ActivityReports",
"RT::Extension::JSGantt",
]
$extensions_list.each |$extls| {
cpan { $extls:
ensure => present,
require => Class['::cpan'],
}
}
As you can see I'm just installing two Perl modules with a cpan module from Puppet Forge. This part works just as expected.
What I would like to happen is each time a new Perl module is installed in this way it will be added to added to the config line of RT (Request Tracker). That file lives here:
/opt/rt4/etc/RT_SiteConfig.pm
and the format of the line is:
Plugins('RT::MODULE::ONE RT::MODULE::TWO');
So, in the end I would like it to look like this:
Plugins('RT::Extension::ActivityReports RT::Extension::JSGantt');
Having Puppet add each new module in turn to that line as they are installed. As in if I decided to install RT::Authen::ExternalAuth a month from now I can just add it to my above iteration and after Puppet runs this:
Plugins('RT::Extension::ActivityReports RT::Extension::JSGantt');
would become this:
Plugins('RT::Extension::ActivityReports RT::Extension::JSGantt RT::Authen::ExternalAuth');
With no other intervention on my part then to add it to the iteration statement.
Assuming that you don't have any other Puppet code managing /opt/rt4/etc/RT_SiteConfig.pm, then you have a few options for making sure that you have the correct Plugins line in that file.
If you only want to manage just that one line then I would recommend using join and a file_line resource from stdlib.
For example:
include stdlib
$ext_string = join($extensions_list, ' ')
file_line { 'rt extensions':
ensure => present,
path => '/opt/rt4/etc/RT_SiteConfig.pm',
line => "Plugins('${ext_string}');",
match => '^\s*Plugins\(',
}
This will add a line containing the list of plugins and will replace any existing plugin line.
If there are several settings that you want to manage then it might make sense to just templatize the entire file. In that case you could simply have the line
Plugins('<%= #extensions_list.join(' ') %>');
in your template.

How to create a JSCS config file on windows

When I try to create a JSCS config file:
C:\Blog\BlogWeb>jscs --auto-configure "C:\Blog\BlogWeb\temp.jscs"
I get the following error:
safeContextKeyword option requires string or array value
What parameter am I supposed to pass? What is a safecontextkeyword?
New to NPM and JSCS, please excuse ignorance.
JSCS was complaining that I didn't have a config file, so I was trying to figure out how to create one.
JSCS looks for a config file in these places, unless you manually specify it with the --config option:
jscs it will consequentially search for jscsConfig option in package.json file then for .jscsrc (which is a just JSON with comments) and .jscs.json files in the current working directory then in nearest ancestor until it hits the system root.
I fixed this by:
Create a new file named .jscsrc. Windows Explorer may not let you do this, so may need to use the command line.
Copy the following into it. It doesn't matter if this is the preset you want to use or not. The command will overwrite it.
{
"preset": "jquery",
"requireCurlyBraces": null // or false
}
Verify that it works by running a command such as:
run the command
jscs --auto-configure .jscsrc

Grunt: How to change config strings for different environments

I have a python file as part of my grunt workflow. I have defined two build tasks:
build:dev
build:release
When I compile 'build:dev', I want to add this line to my python file:
...
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + dbpath
...
When I compile 'build:release', I want to add this line to my python file:
...
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['POSTGRESQL_COLORFUL_URL']
...
edit: fixed typo in code and title
You can use grunt-sed.
It's a really useful 'find and replace' system that builds into Grunt.
From the docs:
npm install grunt-sed
Add this line to your project's Gruntfile.js:
grunt.loadNpmTasks('grunt-sed');
Then in your build:dev and build:release tasks have the following:
sed: {
database_uri: {
path: 'path_to_your_python.py',
pattern: '%PATTERN_IN_YOUR_PYTHON_FILE%',
replacement: '\'sqlite:///\' + dbpath',
}
}
In your python file you want replacing you must also have %PATTERN_IN_YOUR_PYTHON_FILE% to be replaced.
I've used a plugin called grunt-string-replace that worked very well for what I needed to do. Also, I added some custom code in my Gruntfile.js to read different environment configurations and customize the build output based on that.
I detailed the full deployment script in this post: http://dev-blog.cloud-spinners.com/2014/02/complete-grunt-deployment-workflow-for.html
I hope you find that useful.

How do you get the path of the running script in groovy?

I'm writing a groovy script that I want to be controlled via a properties file stored in the same folder. However, I want to be able to call this script from anywhere. When I run the script it always looks for the properties file based on where it is run from, not where the script is.
How can I access the path of the script file from within the script?
You are correct that new File(".").getCanonicalPath() does not work. That returns the working directory.
To get the script directory
scriptDir = new File(getClass().protectionDomain.codeSource.location.path).parent
To get the script file path
scriptFile = getClass().protectionDomain.codeSource.location.path
As of Groovy 2.3.0 the #SourceURI annotation can be used to populate a variable with the URI of the script's location. This URI can then be used to get the path to the script:
import groovy.transform.SourceURI
import java.nio.file.Path
import java.nio.file.Paths
#SourceURI
URI sourceUri
Path scriptLocation = Paths.get(sourceUri)
Note that this will only work if the URI is a file: URI (or another URI scheme type with an installed FileSystemProvider), otherwise a FileSystemNotFoundException will be thrown by the Paths.get(URI) call. In particular, certain Groovy runtimes such as groovyshell and nextflow return a data: URI, which will not typically match an installed FileSystemProvider.
This makes sense if you are running the Groovy code as a script, otherwise the whole idea gets a little confusing, IMO. The workaround is here: https://issues.apache.org/jira/browse/GROOVY-1642
Basically this involves changing startGroovy.sh to pass in the location of the Groovy script as an environment variable.
As long as this information is not provided directly by Groovy, it's possible to modify the groovy.(sh|bat) starter script to make this property available as system property:
For unix boxes just change $GROOVY_HOME/bin/groovy (the sh script) to do
export JAVA_OPTS="$JAVA_OPTS -Dscript.name=$0"
before calling startGroovy
For Windows:
In startGroovy.bat add the following 2 lines right after the line with
the :init label (just before the parameter slurping starts):
#rem get name of script to launch with full path
set GROOVY_SCRIPT_NAME=%~f1
A bit further down in the batch file after the line that says "set
JAVA_OPTS=%JAVA_OPTS% -Dgroovy.starter.conf="%STARTER_CONF%" add the
line
set JAVA_OPTS=%JAVA_OPTS% -Dscript.name="%GROOVY_SCRIPT_NAME%"
For gradle user
I have same issue when I'm starting to work with gradle. I want to compile my thrift by remote thrift compiler (custom by my company).
Below is how I solved my issue:
task compileThrift {
doLast {
def projectLocation = projectDir.getAbsolutePath(); // HERE is what you've been looking for.
ssh.run {
session(remotes.compilerServer) {
// Delete existing thrift file.
cleanGeneratedFiles()
new File("$projectLocation/thrift/").eachFile() { f ->
def fileName=f.getName()
if(f.absolutePath.endsWith(".thrift")){
put from: f, into: "$compilerLocation/$fileName"
}
}
execute "mkdir -p $compilerLocation/gen-java"
def compileResult = execute "bash $compilerLocation/genjar $serviceName", logging: 'stdout', pty: true
assert compileResult.contains('SUCCESSFUL')
get from: "$compilerLocation/$serviceName" + '.jar', into: "$projectLocation/libs/"
}
}
}
}
One more solution. It works perfect even you run the script using GrovyConsole
File getScriptFile(){
new File(this.class.classLoader.getResourceLoader().loadGroovySource(this.class.name).toURI())
}
println getScriptFile()
workaround: for us it was running in an ANT environment and storing some location parent (knowing the subpath) in the Java environment properties (System.setProperty( "dirAncestor", "/foo" )) we could access the dir ancestor via Groovy's properties.get('dirAncestor').
maybe this will help for some scenarios mentioned here.

Resources