How to make a Phonegap plugins installer batch file? - batch-file

I'm trying to develop a batch file that runs a lot of commands of the type of "phonegap local plugin add" for automate the Phonegap plugin installation process when I want to share my app.
I found the following solution developed in linux:
#!/usr/bin/env node
//this hook installs all your plugins
// add your plugins to this list--either
// the identifier, the filesystem location
// or the URL
var pluginlist = [
"org.apache.cordova.device",
"org.apache.cordova.device-motion",
"org.apache.cordova.device-orientation",
"org.apache.cordova.geolocation",
"https://github.com/chrisekelley/AppPreferences/"
];
// no need to configure below
var fs = require('fs');
var path = require('path');
var sys = require('sys')
var exec = require('child_process').exec;
function puts(error, stdout, stderr) {
sys.puts(stdout)
}
pluginlist.forEach(function(plug) {
exec("cordova plugin add " + plug, puts);
});
I'm trying to develop this code in a Windows batch file. Can someone tell me how can I do this?

From a script POV this may be close:
#echo off
for %%a in (
"org.apache.cordova.device"
"org.apache.cordova.device-motion"
"org.apache.cordova.device-orientation"
"org.apache.cordova.geolocation"
"https://github.com/chrisekelley/AppPreferences/"
) do cordova plugin add %%a

Related

"No such file or directory, scandir './command/'"

the error
the code
Please help me fix this, I'm desperately trying to.
You are simply getting this error because in your main.js file, you are expecting the commands to be in the ./commands folder while all the commands are actually in the ./command folder without an s. So all you have to do is either change your command folder's name to commands or you can edit your main.js file and change the command folder's name to ./command like this:
const commandFiles = fs.readdirSync('./command/').filter(file => file.endsWith('.js'))
I will recommend you using glob for command handler npm i glob
With this code you can have file tree like this:
Folder
File in folder
File not in folder
And it will still work well
const { glob } = require('glob')
const { promisify } = require('util');
const globPromise = promisify(glob);
const dir = await globPromise(`${process.cwd()}/commands/**/*.js`);
dir.map((x) => {
const file = require(x)
if(file.name) {
client.commands.set(file.name, file)
}
})
mb u can print "command", not "commandS"

Deploy react on an esp32 with 32 character file name limit

I would like to deploy a react application on a web server on an esp32 micro controller, to control an api on that same micro controller.
The web server is working and can send files and receive requests. The only real problem is that file names of react apps are too long (i.e. ./build/static/js/988.78dc5abd.chunk.js), while the file system on an esp32 is limited to file names no longer than 31 characters.
I tried reducing the file names by editing webpack.config.js, but that doesn't appear to work anymore. I also tried bundling it in a single file which I also could not figure out. Increasing the file name limit also seems impossible.
Does anyone have an idea of how I could deploy a react app on a file system that is limited to file names with 32 characters?
EDIT: The actual best way is to create a custom react webpack and make a tarball with the result
I created a pretty terrible solution to this problem, so if you came across this post, ensure you have exhausted all other options before you attempt to copy this:
Basically I have created a script takes all the files recursively from the react app build directory (rapp/build) and copies them all to the data folder with a number and the correct extension (so the browser picks up the file type):
#!/bin/bash
cd rapp/build
i=0
#clear index and data folder
rm -rf ../../data/*
> ../../data/index
#grab all files and assign number
for f in $(find . -type f -printf '%P\n');
do
#pretty output
RED='\033[0;31m'
NC='\033[0m' # No Color
#grab extension
filename="${f##*/}"
extension="${filename##*.}"
#copy file with number
cp $f "../../data/$i.$extension"
#add original to index
echo $f >> ../../data/index
#add copy to index
echo $i.$extension >> ../../data/index
echo -e $i.$extension ${RED} mapped to ${NC} $f
i=$((i+ 1))
done
then i have created a web server that will automatically redirect all the request to the copied numbered files:
#include "WiFi.h"
#include "SPIFFS.h"
#include "ESPAsyncWebServer.h"
#include <string>
const char* ssid = "abcdef";
const char* password = "";
AsyncWebServer server(80);
void mapRedirect(){
File file = SPIFFS.open("/index");
if (!file) {
Serial.println("Failed to open file for reading");
return;
}
Serial.println("Contents of file:");
int i=0;
while (file.available()) {
String orig=file.readStringUntil('\n');
String cop=file.readStringUntil('\n');
Serial.print(cop);
Serial.print("\tmapped to\t");
Serial.println(orig);
server.on(String("/"+orig).c_str(), HTTP_GET, [cop](AsyncWebServerRequest *request){
request->redirect("/"+String(cop));
}
);
i++;
}
file.close();
}
void setup(){
Serial.begin(115200);
if(!SPIFFS.begin(true)){
Serial.println("An Error has occurred while mounting SPIFFS");
return;
}
WiFi.softAP(ssid,password);
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
request->redirect("/index.html");
});
server.serveStatic("/",SPIFFS,"/");
//redirect react files to coressponding mappings (spiffs character file name limit)
mapRedirect();
server.onNotFound([](AsyncWebServerRequest *request){
request->send(404, "text/plain", "The content you are looking for was not found.");
});
server.begin();
}
void loop(){}

How to perform Git command using variables in Batch via Jenkinsfile

I have the following Jenkinfile content that is able to create the tag name as I want and stored in the varibale 'tag'. How can I use that variable in a batch command here?
Note that Jenkins is on a Windows machine thus using bat command. Am all ears if there is a simple way I could switch to bash. But the main question is as follows. Thank you.
How can I use that 'tag' variable (which has correct value stored before I try to use it in a batch command)? Currently it is coming out with no value with my implementation below trying to echo it.
#!/usr/bin/groovy
pipeline{
agent any
stages {
stage('tag stage'){
steps {
gitTag()
}
}
}
}
def gitTag(){
String date = new Date().format('yyyyMMddhhmmss')
String branch = "${env.GIT_BRANCH}"
String tag = "v${date}-${branch}"
tag = tag.replaceAll('/', '-')
String message = "tagged via jenkins - ${tag}"
print message
bat 'echo Hello test'
bat 'echo from bat before tag %tag% after tag'
bat 'git tag -a %tag% -m "tagging with %message%"'
bat 'git push origin %tag%'
}
Seems due to single quote, groovy is not able to interpolate the variable. Also, use ${var} format. Following should do the trick:
def gitTag(){
String date = new Date().format('yyyyMMddhhmmss')
String branch = "${env.GIT_BRANCH}"
String tag = "v${date}-${branch}"
tag = tag.replaceAll('/', '-')
String message = "tagged via jenkins - ${tag}"
print message
bat "echo from bat before tag ${tag} after tag"
bat "git tag -a ${tag} -m \"tagging with ${message}\""
bat "git push origin ${tag}"
}
I would probably prefer to create the tag in an environment block, then reference the environment tag in my shell script.
def gitTagName(String branch) {
String date = new Date().format('yyyyMMddhhmmss')
String tag = "v${date}-${branch}".replaceAll('/', '-')
return tag
}
pipeline {
agent any
stages {
stage('tag and publish') {
// N.B. this could be inside the "pipeline" block too, depending on scope
environment {
tag = gitTagName(env.GIT_BRANCH)
}
steps {
bat """\
echo from bat before tag ${env.tag} after tag
git tag -a ${tag} -m "tagging with tagged via jenkins - ${tag}"
git push origin ${tag}"""
}
}
}
}
I would probably pull that batch script into your repository while you're at it, though that might be a little over-zealous.

How do I use an EXE in the Chocolatey package from chocolateyInstall.ps1?

I am building a self-contained Chocolatey package. The package folder contains: app.nuspec, app.exe, app.nupkg, and the tools subfolder. The chocolateyInstall.ps1 is like this:
$packageName = 'app'
$fileType = 'exe'
$silentArgs = '/VERYSILENT'
$url = '../app.exe' # the location of the file relative to the tools folder
Install-ChocolateyPackage $packageName $fileType $silentArgs $url
When I run:
choco install app -y
I get:
Copy-Item : cannot find the path C:\ProgramData\app.exe because does not exist
How can I make this work? I've read a bit about 'create self-contained package with shims' but I don't really get how to use that? Any help? thank you
EDIT 1
I have found also this other solution here (http://patrickhuber.github.io/2015/03/19/creating-enterprise-versions-of-public-chocolatey-packages.html) that does work. So in my case that would be:
$directory = $PSScriptRoot
$packageName = 'app'
$fileType = 'exe'
$silentArgs = '/VERYSILENT'
$url = Join-Path $directory '..\app.exe'
Install-ChocolateyPackage $packageName $fileType $silentArgs $url
I was wondering what is the $PSScriptRoot variable?
For doing a Chocolatey Package that contains the exe/msi, you can use the Install-ChocolateyInstallPackage helper method, rather than the Install-ChocolateyPackage helper method. This is documented on the Chocolatey Wiki here
This works in very much the same way as the other helper method, with the exception that it doesn't want/need to download the exe/msi. It uses the path that it is provided, and installs from there.
You can find a complete example of what is required in the ChocolateyGUI package, which does a very similar thing.
The crux of it is shown below for reference:
$packageName = 'ChocolateyGUI'
$fileType = 'msi'
$silentArgs = '/quiet'
$scriptPath = $(Split-Path $MyInvocation.MyCommand.Path)
$fileFullPath = Join-Path $scriptPath 'ChocolateyGUI.msi'
Install-ChocolateyInstallPackage $packageName $fileType $silentArgs $fileFullPath
Somehow we're still missing the explanation of script- and caller-relative paths. In this case, Chocolatey is executing from
%PROGRAMDATA%\Chocolatey\choco.exe
Your script is telling it to go up one level and look for app.exe, that's
%PROGRAMDATA%\app.exe
What Gary's answer implies, by using $MyInvocation is that you need to construct this path relative to the script's location, not the caller's location. You found another method of doing that by joining the path with $PSScriptRoot.
Both of these variables are known as "Automatic variables".
$MyInvocation
Contains an information about the current command, such as the name,
parameters, parameter values, and information about how the command was
started, called, or "invoked," such as the name of the script that called
the current command.
$MyInvocation is populated only for scripts, function, and script blocks.
You can use the information in the System.Management.Automation.InvocationInfo
object that $MyInvocation returns in the current script, such as the path
and file name of the script ($MyInvocation.MyCommand.Path) or the name of a
function ($MyInvocation.MyCommand.Name) to identify the current command.
This is particularly useful for finding the name of the current script.
And
$PSScriptRoot
Contains the directory from which a script is being run.
In Windows PowerShell 2.0, this variable is valid only in script modules
(.psm1). Beginning in Windows PowerShell 3.0, it is valid in all scripts.

Creating a shortcut for a exe using a batch file

I know a topic already exists like that but I do not want to use a VB script.
I would hope you can create a shortcut using a command line in DOS.
Please post some example that would be great.
Thanks!
AA
You can't create a shortcut in a .bat file without invoking an external program.
However, every version of Windows since Win2k has a built in scripting language called Windows Script Host
Here is a small WSH script that I wrote a few years ago that can be called from a .bat file,
just save this text as shortcut.wsf, it contains useage information in the script.
<package>
<job id="MakeShortcut">
<runtime>
<description>Create a shortcut (.lnk) file.</description>
<named
name = "Target"
helpstring = "the target script"
type = "string"
required = "true"
/>
<named
name = "Args"
helpstring = "arguments to pass to the script"
type = "string"
required = "false"
/>
<unnamed
name = "basename"
helpstring = "basename of the lnk file to create"
type = "string"
required = "false"
/>
</runtime>
<script language="JScript">
if ( ! WScript.Arguments.Named.Exists("Target"))
{
WScript.Arguments.ShowUsage();
WScript.Quit(2);
}
target = WScript.Arguments.Named.Item("Target");
WScript.Echo("target " + target);
args = WScript.Arguments.Named.Item("Args");
WScript.Echo("args " + args);
base = WScript.Arguments.Unnamed.Item(0);
WScript.Echo("base " + base);
fso = WScript.CreateObject("Scripting.FileSystemObject");
//path = fso.GetParentFolderName(WScript.ScriptFullName);
path = fso.GetAbsolutePathName(".");
WScript.Echo("path = " + path);
Shell = WScript.CreateObject("WScript.Shell");
short = fso.BuildPath(path,base);
if ( ! fso.GetExtensionName(base))
short = short + ".lnk";
link = Shell.CreateShortcut(short);
link.TargetPath = fso.BuildPath(path, target);
if (args != null && args != "")
link.Arguments = args;
else
link.Arguments = base;
//link.Description = "Sound Forge script link";
//link.HotKey = "ALT+CTRL+F";
//link.IconLocation = fso.BuildPath(path, target) + ", 2";
//link.WindowStyle = "1"
//link.WorkingDirectory = path;
link.Save();
</script>
</job>
</package>
run it without any arguments to get useage
c:\> shortcut.wsf
Microsoft (R) Windows Script Host Version 5.6
Copyright (C) Microsoft Corporation 1996-2001. All rights reserved.
Create a shortcut (.lnk) file.
Usage: shortcut.wsf /Target:value [/Args:value] [basename]
Options:
Target : the target script
Args : arguments to pass to the script
basename : basename of the lnk file to create
mklink /D c:\vim "C:\Program Files (x86)\Vim"
More Info Here
And Cygwin's ln - s
http://en.wikipedia.org/wiki/Symbolic_link#Cygwin_symbolic_links
Creating a shortcut in the .lnk format is basically impossible from a batch file without calling an external program of some kind. The file spec can be found here, and a quick glace will explain.
Creating a .url format shortcut is quite easy as the format is a simple text file. The spec can be found here. This format has a few disadvantages, but may accomplish your goal.
you can get shortcut.exe from the resource kit.
It can now be done with Powershell, which arguably sucks somewhat less than VBscript. And powershell can be called from a .bat / .cmd file:
powershell "$s=(New-Object -COM WScript.Shell).CreateShortcut('%userprofile%\Desktop\mylink.lnk'); $s.TargetPath='C:\Path\to\your.exe'; $s.Save()"
See also here for another example: https://ss64.com/nt/shortcut.html#e
See also

Resources