Batch script: Convert path to linux format using wslpath - batch-file

I was trying to convert current working directory of a .bat script into linux format by using wsl wslpath. To show you it works on CMD:
However, when I put it in a .bat file, and changed %cd% to %~dp0, the path is empty:
test.bat contains:
FOR /F %%i IN ('wsl wslpath -a %~dp0') DO set lp=%%i
echo %lp%
Any idea why?

Try this:
echo "%cd%" -- "%~dp0"
%cd% returns the path without ending backslash. So you can add a second variable that clears it.
set "scriptDir=%~dp0"
set "scriptDir=%scriptDir:~0,-1%"
UPDATE (with string substitution only - use the toLinuxPath subroutine)
#echo off
call ::toLinuxPath "%userprofile%\AppData\Local\Temp" tempF
echo %tempF%
exit /b 0
:toLinuxPath [returnVariable - the result will be stored in it; If omitted will be only echoed]
setlocal
set "_path=%~p1"
set "name=%~nx1"
set "drive=%~d1"
set "rtrn=%~2"
set "result=/mnt/%drive:~0,1%%_path:\=/%%name%"
endlocal & (
if "%~2" neq "" (
set "%rtrn%=%result%"
) else (
echo %result%
)
)

Related

Batch script to read input text file and build output command

I have a batch file that will run csc using a file as input. I want to modify it to read references from a file, and add them to the line that is executed when the script runs.
I've tried a few different things but can't seem to get it work. The references are added with /r: and then each reference path has semi-colon as a separator.
Ideally, I'd like to just have a reference on a new line in the text file. The ref.txt file is in the same directory as the input file, and I'm not sure if it was looking in this directory or not. I also want to make it attempt to run without the ref.txt file, so I added the exists line to do this. I've never used batch scripting before, so maybe someone else knows how to do this better than me. I think that the first line needs to match the start line, which I tried to do in other attempts, but it wasn't working.
The script works in Notepad++, and was from this answer. I think now that the run command also needs to be modified.
This is the run command in Notepad++:
C:\bin\csc.bat "$(CURRENT_DIRECTORY)\$(NAME_PART).exe" "$(FULL_CURRENT_PATH)"
This is the version from that answer:
C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc /out:%1 %2
#echo off
if errorlevel 1 (
pause
exit
)
start %1 %1
This is an attempt to use references:
C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc /out:%1 %2
#echo off
if errorlevel 1 (
pause
exit
)
if not exist ref.txt GOTO :write
set a = /r:
set refs = type ref.txt
start %1 %a% and %refs% and %1
exit
write
start %1 %1
The refs.txt file contains file paths like this:
C:\windows\some_path\some_file.dll;C:\windows\some_path\another_file.dll;
An example command from Microsoft is:
csc /t:exe /r:MyCodeLibrary.dll;NewLib.dll *.cs
IIUR you are trying to apply the refs to the compiled exe not to csc itself.
You need to adapt the path to the ref.txt file
:: Q:\Test\2019\01\25\SO_54360791.cmd
#echo off & Setlocal EnableDelayedExpansion
Set CSC="C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe"
Set Ref=".\ref.txt"
if exist %Ref% (
<%Ref% Set /p "refs="
set "refs=/r:!refs!"
) else set "refs="
%CSC% %refs% /out:%1 %2
if errorlevel 1 (
pause
exit
)
sample (echoed) output
> SO_54360791.cmd new.exe source.cs
"C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe" /r:C:\windows\some_path\some_file.dll;C:\windows\some_path\another_file.dll; /out:new.exe source.cs
I'm not sure if the trailing semicolon in your sample ref.txt will work.
EDIT: Variant with ref.txt file containing quoted pathes with trailing semiclon
:: Q:\Test\2019\01\25\SO_54360791.cmd
#echo off & Setlocal EnableDelayedExpansion
Set CSC="C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe"
Set Ref=".\ref.txt"
Set "refs="
if not exist %Ref% goto :cont
set "refs=/r:"
for /f "usebackq delims=" %%A in (%Ref%) Do set "refs=!refs!%%A"
:cont
echo %CSC% %refs% /out:%1 %2
if errorlevel 1 (
pause
exit
)
goto :Eof
sample (echoed) output
> SO_54360791.cmd new.exe source.cs
"C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe" /r:"C:\windows\some_path\some_file.dll";"C:\windows\some_path\another_file.dll"; /out:new.exe source.cs

A common batch file to setup variables

I am working on multiple batch files and I want them to share some variables, so I created a batch file that has all these setups SetupEnv:
rem General setup
:: To pause or not after running a batch file
SET isPause = true
:: The directory where your source code is located
SET directory = D
:: The folders where your primary & secondary source code is located
:: I like to have two source code folders, if you don't then just have them pointing to the same folder
SET primary_source_code = \Dev\App
SET secondary_source_code = \Dev\App2
:::::::::::::::::::::::::::::::::::::::::::: XAMPP :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
rem If you're using XAMPP then set these up
:: Your destination folder
SET base_destination = C:\xampp\htdocs
:: The base url that is pointing to your destination folder (in most cases it's localhost)
SET base_url = http://10.0.2.65
:::::::::::::::::::::::::::::::::::::::::: Angular :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
rem If you're using angular set these up
:: The folder where you built code is copied
SET build_file = dist
And from another batch file I'm calling that file first:
::setup
call ../SetupEnv
echo %directory% dir
pause;
The problem is that even though the file runs smoothly and I can see in the outputs that things are being setup, the variables are not coming across to the file I'm calling it from. So in that example %directory% is not being printed.
EDIT
I also tried using Joey's answer:
::setup
for /f "delims=" %%x in (../SetupEnv.txt) do (set "%%x")
echo %directory% dir
pause
But that didn't work either and %directory% didn't get printed
setting variables in a called batchfile works, as long as you don't use setlocal in the called batchfile (there will be an implicite endlocal, when it returns, so the variables would get lost):
> type a.bat
set var=old
echo %var%
call b.bat
echo %var%
> type b.bat
set var=new
> a.bat
> set var=old
> echo old
old
> call b.bat
> set var=new
> echo new
new
>
for the alternative for solution, I would slightly change it to:
for /f "delims=" %%a in ('type b.bat^|findstr /bic:"set "') do %%a
This will only "execute" lines, that start with set (ignoring capitalization), so you can keep any comments inside that file.
Note: ... do set "%%a" adds another set to the line (you have already one in the file), resulting in set "set var=value", which you obviously don't want.
May be it's a bit too late, but nevertheless.
I've a loader script implementation to load a configuration file with a common format between Windows Batch and Unix Bash Shell scripts.
Format description:
# FORMAT:
# [<attributes>] <variable>[:[<class_name>]]=<value>
#
# <attributes>: Variable space separated attributes: export
# <variable>: Variable name corresponding to the regex: [_a-zA-Z][_a-zA-Z0-9]*
# <class_name>: class variant name: OSWIN | OSUNIX | BAT | SH
# OSWIN: Apply on Windows system including cygwin/mingw/msys subsystems.
# OSUNIX: Apply on Unix/Linux systems excluding cygwin/mingw/msys subsystems.
# BAT: Apply on Windows system when this file has loaded from the Windows batch script loader.
# SH: Apply on any system when this file has loaded from the Bash shell script loader.
#
# <value>: Can start by the `"` quote character, but two quotes does remove only when exist on both ends of a value.
#
Note: The export attribute has meaning only in the Unix Shell parser.
config file example:
export PYTHON_EXE_PATH:OSWIN="c:/python/x86/38/python.exe"
export PYTHON_EXE_PATH:OSUNIX=python3
export PYTHONDONTWRITEBYTECODE=1
MY_SHELL_SCRIPT:BAT=blabla.bat
MY_SHELL_SCRIPT:SH=blabla.sh
usage example:
call load_config.bat . . myvars.vars
This will generate the myvars.vars from the myvars.vars.in file and load it.
The script does generate an instance configuration file from a template file before parse an instance file. Implementation a bit complicated and might change in the future:
https://github.com/andry81/contools/tree/HEAD/Scripts/Tools/build/load_config.bat
https://github.com/andry81/contools/tree/HEAD/Scripts/Tools/build/.load_config
CAUTION:
Seems the stackoverflow incorrectly handles tabulation characters (and loses other characters like \x01) in the copy-pasted code, so the below code might not work if you copy it directly by CTRL+C. Use links above to directly download the script.
Old implementation (just for example):
#echo off
setlocal DISABLEDELAYEDEXPANSION
set "__CONFIG_IN_DIR=%~1"
set "__CONFIG_OUT_DIR=%~2"
set "__CONFIG_FILE=%~3"
if not defined __CONFIG_IN_DIR (
echo.%~nx0: error: input config directory is not defined.
exit /b 1
) >&2
if not defined __CONFIG_OUT_DIR (
echo.%~nx0: error: output config directory is not defined.
exit /b 2
) >&2
set "__CONFIG_IN_DIR=%__CONFIG_IN_DIR:\=/%"
set "__CONFIG_OUT_DIR=%__CONFIG_OUT_DIR:\=/%"
if "%__CONFIG_IN_DIR:~-1%" == "/" set "__CONFIG_IN_DIR=%__CONFIG_IN_DIR:~0,-1%"
if "%__CONFIG_OUT_DIR:~-1%" == "/" set "__CONFIG_OUT_DIR=%__CONFIG_OUT_DIR:~0,-1%"
if not exist "%__CONFIG_IN_DIR%\" (
echo.%~nx0: error: input config directory does not exist: "%__CONFIG_IN_DIR%".
exit /b 10
) >&2
if not exist "%__CONFIG_OUT_DIR%\" (
echo.%~nx0: error: output config directory does not exist: "%__CONFIG_OUT_DIR%".
exit /b 11
) >&2
if not exist "%__CONFIG_OUT_DIR%\%__CONFIG_FILE%" ^
if exist "%__CONFIG_IN_DIR%/%__CONFIG_FILE%.in" (
echo."%__CONFIG_IN_DIR%/%__CONFIG_FILE%.in" -^> "%__CONFIG_OUT_DIR%/%__CONFIG_FILE%"
type "%__CONFIG_IN_DIR:/=\%\%__CONFIG_FILE%.in" > "%__CONFIG_OUT_DIR%/%__CONFIG_FILE%"
)
rem load configuration files
if not exist "%__CONFIG_OUT_DIR%/%__CONFIG_FILE%" (
echo.%~nx0: error: config file is not found: "%__CONFIG_OUT_DIR%/%__CONFIG_FILE%".
exit /b 20
) >&2
for /F "usebackq eol=# tokens=* delims=" %%i in ("%__CONFIG_OUT_DIR%/%__CONFIG_FILE%") do (
endlocal
setlocal DISABLEDELAYEDEXPANSION
for /F "eol=# tokens=1,* delims==" %%j in ("%%i") do (
set "__VAR=%%j"
set "__VALUE=%%k"
call :PARSE_EXPR && (
setlocal ENABLEDELAYEDEXPANSION
for /F "tokens=1,* delims==" %%i in ("!__VAR!=!__VALUE!") do (
endlocal
endlocal
set "%%i=%%j"
)
type nul>nul
) || endlocal
)
)
exit /b 0
:PARSE_EXPR
if not defined __VAR exit /b 1
rem CAUTION:
rem Inplace trim of surrounded white spaces ONLY from left and right sequences as a whole for performance reasons.
rem
:TRIM_VAR_NAME
:TRIM_VAR_NAME_LEFT_LOOP
if not defined __VAR exit /b 1
if not ^%__VAR:~0,1%/ == ^ / if not ^%__VAR:~0,1%/ == ^ / goto TRIM_VAR_NAME_RIGHT_LOOP
set "__VAR=%__VAR:~1%"
goto TRIM_VAR_NAME_LEFT_LOOP
:TRIM_VAR_NAME_RIGHT_LOOP
if not ^%__VAR:~-1%/ == ^ / if not ^%__VAR:~-1%/ == ^ / goto TRIM_VAR_NAME_RIGHT_LOOP_END
set "__VAR=%__VAR:~0,-1%"
if not defined __VAR exit /b 1
goto TRIM_VAR_NAME_RIGHT_LOOP
:TRIM_VAR_NAME_RIGHT_LOOP_END
if not defined __VALUE exit /b 0
rem Replace a value quote characters by the \x01 character.
set "__VALUE=%__VALUE:"=%"
:TRIM_VAR_VALUE
setlocal DISABLEDELAYEDEXPANSION
:TRIM_VAR_VALUE_LEFT_LOOP
if not defined __VALUE exit /b 0
if not ^%__VALUE:~0,1%/ == ^ / if not ^%__VALUE:~0,1%/ == ^ / goto TRIM_VAR_VALUE_RIGHT_LOOP
set "__VALUE=%__VALUE:~1%"
goto TRIM_VAR_VALUE_LEFT_LOOP
:TRIM_VAR_VALUE_RIGHT_LOOP
if not ^%__VALUE:~-1%/ == ^ / if not ^%__VALUE:~-1%/ == ^ / goto TRIM_VAR_VALUE_RIGHT_LOOP_END
set "__VALUE=%__VALUE:~0,-1%"
if not defined __VALUE exit /b 0
goto TRIM_VAR_VALUE_RIGHT_LOOP
:TRIM_VAR_VALUE_RIGHT_LOOP_END
(
endlocal
set "__VALUE=%__VALUE%"
)
for /F "eol= tokens=1,* delims=:" %%i in ("%__VAR%") do (
set "__VAR=%%i"
set "__PLATFORM=%%j"
)
if not defined __VAR exit /b 1
if defined __PLATFORM ^
if not "%__PLATFORM%" == "BAT" ^
if not "%__PLATFORM%" == "WIN" ^
if not "%__PLATFORM%" == "OSWIN" exit /b 1
for /F "eol=# tokens=1,* delims= " %%i in ("%__VAR%") do (
set "__ATTR=%%i"
set "__VAR=%%j"
)
if not defined __VAR (
set "__VAR=%__ATTR%"
set "__ATTR="
)
if not defined __VAR exit /b 1
if ^/ == ^%__VALUE:~1,1%/ goto PREPARSE_VALUE
if not ^/ == ^%__VALUE:~0,1%/ goto PREPARSE_VALUE
if not ^/ == ^%__VALUE:~-1%/ goto PREPARSE_VALUE
:REMOVE_QUOTES
for /F "tokens=* delims=" %%i in ("%__VALUE:~1,-1%") do set "__VALUE=%%i"
if not defined __VALUE exit /b 0
goto PARSE_VALUE
:PREPARSE_VALUE
set __HAS_VALUE=0
for /F "eol=# tokens=* delims=" %%i in ("%__VALUE%") do set "__HAS_VALUE=1"
if %__HAS_VALUE% EQU 0 (
set "__VALUE="
exit /b 0
)
:PARSE_VALUE
rem recode quote and exclamation characters
set "__ESC__=^"
set __QUOT__=^"
set "__EXCL__=!"
set "__VALUE=%__VALUE:!=!__EXCL__!%"
set "__VALUE=%__VALUE:^=!__ESC__!%"
set "__VALUE=%__VALUE:=!__QUOT__!%"
exit /b 0

batch download images from url with for

I need to download 300 images from site.com/folder/ using the following format: 1.png, 2.png ... 300.png
Is there a way to do this inside a batch file or using the command prompt?
Wth curl like this:
curl -o "#1.png" http://example.com/folder/[1-300].png
Here is an example to download some batch codes from a file that can be created by this script if not exist, and of course you can add or modify what you want of urls in this file !
You can add your urls in the text file named Urls.txt
Firstly, the script check for the text file named Urls.txt if exist in same location where this batch is executed and read from it the urls line by line to download them !
So, if you want to change those urls to yours, just change it from the text file Urls.txt not from the batch, i mean you can create a text file and name it to Urls.txt and put what you want as urls on this file line by line of course and let the script do its job
#echo off
Mode 110,3 & color 0A
Title Download file from web using powershell and batch by Hackoo 2017
Set "List_Urls_File=Urls.txt"
If not exist "%List_Urls_File%" Call :Create_Urls_File
Setlocal enabledelayedexpansion
#For /f "delims=" %%a in ('Type "%List_Urls_File%"') do (
Set "URL=%%a"
Rem we set the Filename from the variable !url!
#for %%# in (!url!) do ( set "File=%%~xn#" )
Rem Check if the file name contains a dot "."
Rem If not we increment the counter +1 for file to be download
ECHO !File! | FIND /I ".">Nul 2>&1
If "!errorlevel!" NEQ "0" (
Set /a Count+=1
cls & echo(
echo Downloading file "File-!Count!.bat" from URL : "!URL!"
Call :BalloonTip 'information' 10 '"Downloading File-!Count!.bat"' "'Please wait... Downloading File-!Count!.bat....'" 'info' 4
Call :Download "%%a" "File-!Count!.bat"
) else (
cls & echo(
echo Downloading file "!File!" from URL : "!URL!"
Call :BalloonTip 'information' 10 '"Downloading !File!"' "'Please wait... Downloading !File!....'" 'info' 4
Call :Download "%%a" "!File!"
)
)
Explorer "%~dp0" & exit
::*********************************************************************************
:Download <url> <File>
Powershell.exe -command "(New-Object System.Net.WebClient).DownloadFile('%1','%2')"
exit /b
::*********************************************************************************
:Create_Urls_File
(
echo https://pastebin.com/raw/XvyhRzT6
echo https://pastebin.com/raw/QqnZ0MjQ
echo https://pastebin.com/raw/tHsKw15V
echo https://pastebin.com/raw/VCnTbLB6
echo https://pastebin.com/raw/3zUTrWUz
echo https://pastebin.com/raw/31auQeFz
echo https://pastebin.com/raw/xF0uXThH
echo https://pastebin.com/raw/uzsGQD1h
echo https://pastebin.com/raw/3TmVYiZJ
echo https://pastebin.com/raw/Ntc8SZLU
echo https://pastebin.com/raw/jnpRBhwn
echo https://www.virustotal.com/static/bin/vtuploader2.2.exe
echo http://devbuilds.kaspersky-labs.com/devbuilds/KVRT/latest/full/KVRT.exe
)>"%List_Urls_File%"
exit /b
::*********************************************************************************
:BalloonTip $notifyicon $time $title $text $icon $Timeout
PowerShell ^
[reflection.assembly]::loadwithpartialname('System.Windows.Forms') ^| Out-Null; ^
[reflection.assembly]::loadwithpartialname('System.Drawing') ^| Out-Null; ^
$notify = new-object system.windows.forms.notifyicon; ^
$notify.icon = [System.Drawing.SystemIcons]::%1; ^
$notify.visible = $true; ^
$notify.showballoontip(%2,%3,%4,%5); ^
Start-Sleep -s %6; ^
$notify.Dispose()
%End PowerShell%
exit /B
::*************************************************************************
Numbered-Files Downloader 1.0
Here is a complete batch script that is doing exactly what you asked for. You don't need to download any executable files, this is 100% batch script and it should works on any (recent) Windows installation.
All you need to do is to edit the _URL variable (Line 11) and replace "example.com/folder..." with the actual URL of the files you want to download. After that, you can run the script and get your files.
Note that in your URL, this string: _NUMBERS_ is a keyword-filter that will be replaced by the incremented numbers in the final download function.
All your downloaded files will be saved in the directory where this script is located. You can choose an other directory by uncommenting the _SAVE_PATH variable (Line 15).
Finally the following variables can be changed to configure the series of numbers:
_START : The file numbers starts with this value.
_STEP   : Step between each files.
_END    : The file numbers ends with this value.
Leading Zeros
Currently, the counter doesn't support leading zeros.
EX. From Picture_001.jpg to Picture_999.jpg
But otherwise it should work fine for something like this:
EX. From Picture_1.jpg to Picture_999.jpg
I will try to find some time to add this option, it shouldn't be too difficult.
Feel free to modify & enhance this script if you need!
Numbered-DL.cmd
#echo off
setlocal EnableDelayedExpansion
rem STACKOVERFLOW - QUESTION FROM:
rem https://stackoverflow.com/questions/45796990/batch-download-images-from-url-with-for
:VARIABLES
rem WHERE YOU WANT TO SAVE FILES
rem "%~dp0" is a variable for the same folder as this script, so files should be saved in the same folder.
rem If you want to save the downloaded files somewhere else, uncomment the next line and edit the path.
SET "_SAVE_DIR=%~dp0"
rem SET _SAVE_PATH=C:\Folder\
rem DOWNLOAD THIS FILE URL
rem
rem "_NUMBERS_" WILL BE REPLACED BY THE COUNTER
rem CURRENLY IT DOESN'T SUPPORT CHOOSING A NUMBERS OF ZEROS FOR THE COUNTER EX: 001,002,003...
rem BUT IT SHOULDN'T BE TOO HARD TO IMPLEMENT, MAYBE ILL ADD THIS IN THE FUTURE.
rem
rem SET _FILE_URL=https://example.com/folder/_NUMBERS_.png
SET "_FILE_URL=https://cweb.canon.jp/eos/lineup/r5/image/downloads/sample0_NUMBERS_.jpg"
rem FOR THIS EXAMPLE THE SCRIPT WILL DOWNLOAD FILES FROM "sample01.jpg" TO "sample05.jpg"
SET _START=1
SET _STEP=1
SET _END=5
:CMD_PARAMS
IF NOT [%1]==[] SET "_FILE_URL=%1"
IF NOT [%2]==[] SET "_SAVE_DIR=%2"
:PATH_FIX
rem REMOVE THE LAST CHAR IF IT IS "\"
IF [%_SAVE_DIR:~-1%] == [\] SET "_SAVE_DIR=%_SAVE_DIR:~0,-1%"
:DETAILS_DISPLAY
ECHO.
ECHO SCRIPT: Numbered-Files Downloader 1.0
ECHO AUTHOR: Frank Einstein
ECHO.
ECHO.
ECHO INPUTS
ECHO _URL: %_FILE_URL%
ECHO _SAVE_DIR: %_SAVE_DIR%
ECHO.
ECHO _START: %_START%
ECHO _STEP= %_STEP%
ECHO _END= %_END%
ECHO.
ECHO.
CALL :DOWNLOAD_LOOP
ECHO.
ECHO EXECUTION COMPLETED
ECHO.
PAUSE
EXIT /B
:DOWNLOAD_LOOP
SET FINAL_URL=%_FILE_URL%
FOR /L %%G IN (%_START%,%_STEP%,%_END%) DO (
rem REPLACE URL'S KEYWORD WITH NUMBERS
SET NUM=%%G
SET FINAL_URL=%FINAL_URL:_NUMBERS_=!NUM!%
rem CUMSTOM BATCH FUNCTION FOR DOWNLOADING FILES
rem
rem SYNTAX:
rem echo CALL :DOWNLOAD !FINAL_URL!
CALL :DOWNLOAD !FINAL_URL! !_SAVE_DIR!
)
Goto :EOF
rem PAUSE
rem EXIT /B
rem FUNCTIONS
:DOWNLOAD
setlocal
SET "DL_FILE_URL=%1"
SET "DL_SAVE_DIR=%2"
rem EXTRACT THE FILENAME FROM URL (NEED TO FIX THIS PART?)
FOR %%F IN ("%DL_FILE_URL%") DO SET DL_FILE_NAME=%%~nxF
IF "%DL_SAVE_DIR:~-1%" == "\" SET "DL_SAVE_DIR=%DL_SAVE_DIR:~0,-1%"
IF NOT [%2]==[] SET "DL_SAVE_FILE=%DL_SAVE_DIR%\%DL_FILE_NAME%"
IF [%2]==[] SET "DL_SAVE_FILE=%~dp0%DL_FILE_NAME%"
rem :BITSADMIN
ECHO.
ECHO DOWNLOADING: "%DL_FILE_URL%"
ECHO SAVING TO: "%DL_SAVE_FILE%"
ECHO.
bitsadmin /transfer mydownloadjob /download /priority foreground "%DL_FILE_URL%" "%DL_SAVE_FILE%"
rem BITSADMIN DOWNLOAD EXAMPLE
rem bitsadmin /transfer mydownloadjob /download /priority foreground http://example.com/filename.zip C:\Users\username\Downloads\filename.zip
endlocal
GOTO :EOF
try with winhttpjs.bat:
set "baseLink=http://example.org/folder/"
for /l %%a in (1;1;300) do (
winhttpjs.bat "%baseLink%%%a.png" -saveto %%a.png
)

Generate war from play application

I'm trying to generate a war file in play application.
I am using starter java project: play-java-starter-example. Play version 2.6.2 in Windows.
I added the plugin play2war in project/plugins.sbt:
addSbtPlugin("com.github.play2war" % "play2-war-plugin" % "1.4.0")
After that I ran the following commands:
C:\project_name>sbt
[project_name]$ dist
It generates a zip file as it's supposed to.
The next step according to the official Doc is to execute a .bat file inside target/universal/[project_name]/bin
Im stuck at this step, execution of the script gives the following message:
console output
Here is the content of the .bat file generated by the dist command:
#REM play-java-starter-example launcher script
#REM
#REM Environment:
#REM JAVA_HOME - location of a JDK home dir (optional if java on path)
#REM CFG_OPTS - JVM options (optional)
#REM Configuration:
#REM PLAY_JAVA_STARTER_EXAMPLE_config.txt found in the PLAY_JAVA_STARTER_EXAMPLE_HOME.
#setlocal enabledelayedexpansion
#echo off
if "%PLAY_JAVA_STARTER_EXAMPLE_HOME%"=="" set "PLAY_JAVA_STARTER_EXAMPLE_HOME=%~dp0\\.."
set "APP_LIB_DIR=%PLAY_JAVA_STARTER_EXAMPLE_HOME%\lib\"
rem Detect if we were double clicked, although theoretically A user could
rem manually run cmd /c
for %%x in (!cmdcmdline!) do if %%~x==/c set DOUBLECLICKED=1
rem FIRST we load the config file of extra options.
set "CFG_FILE=%PLAY_JAVA_STARTER_EXAMPLE_HOME%\PLAY_JAVA_STARTER_EXAMPLE_config.txt"
set CFG_OPTS=
if exist "%CFG_FILE%" (
FOR /F "tokens=* eol=# usebackq delims=" %%i IN ("%CFG_FILE%") DO (
set DO_NOT_REUSE_ME=%%i
rem ZOMG (Part #2) WE use !! here to delay the expansion of
rem CFG_OPTS, otherwise it remains "" for this loop.
set CFG_OPTS=!CFG_OPTS! !DO_NOT_REUSE_ME!
)
)
rem We use the value of the JAVACMD environment variable if defined
set _JAVACMD=%JAVACMD%
if "%_JAVACMD%"=="" (
if not "%JAVA_HOME%"=="" (
if exist "%JAVA_HOME%\bin\java.exe" set "_JAVACMD=%JAVA_HOME%\bin\java.exe"
)
)
if "%_JAVACMD%"=="" set _JAVACMD=java
rem Detect if this java is ok to use.
for /F %%j in ('"%_JAVACMD%" -version 2^>^&1') do (
if %%~j==java set JAVAINSTALLED=1
if %%~j==openjdk set JAVAINSTALLED=1
)
rem BAT has no logical or, so we do it OLD SCHOOL! Oppan Redmond Style
set JAVAOK=true
if not defined JAVAINSTALLED set JAVAOK=false
if "%JAVAOK%"=="false" (
echo.
echo A Java JDK is not installed or can't be found.
if not "%JAVA_HOME%"=="" (
echo JAVA_HOME = "%JAVA_HOME%"
)
echo.
echo Please go to
echo http://www.oracle.com/technetwork/java/javase/downloads/index.html
echo and download a valid Java JDK and install before running play-java-starter-example.
echo.
echo If you think this message is in error, please check
echo your environment variables to see if "java.exe" and "javac.exe" are
echo available via JAVA_HOME or PATH.
echo.
if defined DOUBLECLICKED pause
exit /B 1
)
rem We use the value of the JAVA_OPTS environment variable if defined, rather than the config.
set _JAVA_OPTS=%JAVA_OPTS%
if "!_JAVA_OPTS!"=="" set _JAVA_OPTS=!CFG_OPTS!
rem We keep in _JAVA_PARAMS all -J-prefixed and -D-prefixed arguments
rem "-J" is stripped, "-D" is left as is, and everything is appended to JAVA_OPTS
set _JAVA_PARAMS=
set _APP_ARGS=
:param_loop
call set _PARAM1=%%1
set "_TEST_PARAM=%~1"
if ["!_PARAM1!"]==[""] goto param_afterloop
rem ignore arguments that do not start with '-'
if "%_TEST_PARAM:~0,1%"=="-" goto param_java_check
set _APP_ARGS=!_APP_ARGS! !_PARAM1!
shift
goto param_loop
:param_java_check
if "!_TEST_PARAM:~0,2!"=="-J" (
rem strip -J prefix
set _JAVA_PARAMS=!_JAVA_PARAMS! !_TEST_PARAM:~2!
shift
goto param_loop
)
if "!_TEST_PARAM:~0,2!"=="-D" (
rem test if this was double-quoted property "-Dprop=42"
for /F "delims== tokens=1,*" %%G in ("!_TEST_PARAM!") DO (
if not ["%%H"] == [""] (
set _JAVA_PARAMS=!_JAVA_PARAMS! !_PARAM1!
) else if [%2] neq [] (
rem it was a normal property: -Dprop=42 or -Drop="42"
call set _PARAM1=%%1=%%2
set _JAVA_PARAMS=!_JAVA_PARAMS! !_PARAM1!
shift
)
)
) else (
if "!_TEST_PARAM!"=="-main" (
call set CUSTOM_MAIN_CLASS=%%2
shift
) else (
set _APP_ARGS=!_APP_ARGS! !_PARAM1!
)
)
shift
goto param_loop
:param_afterloop
set _JAVA_OPTS=!_JAVA_OPTS! !_JAVA_PARAMS!
:run
set "APP_CLASSPATH=%APP_LIB_DIR%\..\conf\;%APP_LIB_DIR%\play-java-starter-example.play-java-starter-example-1.0-SNAPSHOT-sans-externalized.jar;%APP_LIB_DIR%\org.scala-lang.scala-library-2.12.2.jar;%APP_LIB_DIR%\com.typesafe.play.twirl-api_2.12-1.3.3.jar;%APP_LIB_DIR%\org.scala-lang.modules.scala-xml_2.12-1.0.6.jar;%APP_LIB_DIR%\com.typesafe.play.play-server_2.12-2.6.2.jar;%APP_LIB_DIR%\com.typesafe.play.play_2.12-2.6.2.jar;%APP_LIB_DIR%\com.typesafe.play.build-link-2.6.2.jar;%APP_LIB_DIR%\com.typesafe.play.play-exceptions-2.6.2.jar;%APP_LIB_DIR%\com.typesafe.play.play-netty-utils-2.6.2.jar;%APP_LIB_DIR%\org.slf4j.slf4j-api-1.7.25.jar;%APP_LIB_DIR%\org.slf4j.jul-to-slf4j-1.7.25.jar;%APP_LIB_DIR%\org.slf4j.jcl-over-slf4j-1.7.25.jar;%APP_LIB_DIR%\com.typesafe.play.play-streams_2.12-2.6.2.jar;%APP_LIB_DIR%\org.reactivestreams.reactive-streams-1.0.0.jar;%APP_LIB_DIR%\com.typesafe.akka.akka-stream_2.12-2.5.3.jar;%APP_LIB_DIR%\com.typesafe.akka.akka-actor_2.12-2.5.3.jar;%APP_LIB_DIR%\com.typesafe.config-1.3.1.jar;%APP_LIB_DIR%\org.scala-lang.modules.scala-java8-compat_2.12-0.8.0.jar;%APP_LIB_DIR%\com.typesafe.ssl-config-core_2.12-0.2.1.jar;%APP_LIB_DIR%\org.scala-lang.modules.scala-parser-combinators_2.12-1.0.6.jar;%APP_LIB_DIR%\com.typesafe.akka.akka-slf4j_2.12-2.5.3.jar;%APP_LIB_DIR%\com.fasterxml.jackson.core.jackson-core-2.8.9.jar;%APP_LIB_DIR%\com.fasterxml.jackson.core.jackson-annotations-2.8.9.jar;%APP_LIB_DIR%\com.fasterxml.jackson.core.jackson-databind-2.8.9.jar;%APP_LIB_DIR%\com.fasterxml.jackson.datatype.jackson-datatype-jdk8-2.8.9.jar;%APP_LIB_DIR%\com.fasterxml.jackson.datatype.jackson-datatype-jsr310-2.8.9.jar;%APP_LIB_DIR%\commons-codec.commons-codec-1.10.jar;%APP_LIB_DIR%\com.typesafe.play.play-json_2.12-2.6.2.jar;%APP_LIB_DIR%\com.typesafe.play.play-functional_2.12-2.6.2.jar;%APP_LIB_DIR%\org.scala-lang.scala-reflect-2.12.2.jar;%APP_LIB_DIR%\org.typelevel.macro-compat_2.12-1.1.1.jar;%APP_LIB_DIR%\joda-time.joda-time-2.9.9.jar;%APP_LIB_DIR%\com.google.guava.guava-22.0.jar;%APP_LIB_DIR%\com.google.code.findbugs.jsr305-1.3.9.jar;%APP_LIB_DIR%\com.google.errorprone.error_prone_annotations-2.0.18.jar;%APP_LIB_DIR%\com.google.j2objc.j2objc-annotations-1.1.jar;%APP_LIB_DIR%\org.codehaus.mojo.animal-sniffer-annotations-1.14.jar;%APP_LIB_DIR%\io.jsonwebtoken.jjwt-0.7.0.jar;%APP_LIB_DIR%\org.apache.commons.commons-lang3-3.6.jar;%APP_LIB_DIR%\javax.transaction.jta-1.1.jar;%APP_LIB_DIR%\javax.inject.javax.inject-1.jar;%APP_LIB_DIR%\com.typesafe.play.play-java-forms_2.12-2.6.2.jar;%APP_LIB_DIR%\com.typesafe.play.play-java_2.12-2.6.2.jar;%APP_LIB_DIR%\org.reflections.reflections-0.9.11.jar;%APP_LIB_DIR%\org.javassist.javassist-3.21.0-GA.jar;%APP_LIB_DIR%\net.jodah.typetools-0.5.0.jar;%APP_LIB_DIR%\org.hibernate.hibernate-validator-5.4.1.Final.jar;%APP_LIB_DIR%\javax.validation.validation-api-1.1.0.Final.jar;%APP_LIB_DIR%\org.jboss.logging.jboss-logging-3.3.0.Final.jar;%APP_LIB_DIR%\com.fasterxml.classmate-1.3.1.jar;%APP_LIB_DIR%\org.springframework.spring-context-4.3.9.RELEASE.jar;%APP_LIB_DIR%\org.springframework.spring-core-4.3.9.RELEASE.jar;%APP_LIB_DIR%\org.springframework.spring-beans-4.3.9.RELEASE.jar;%APP_LIB_DIR%\com.typesafe.play.filters-helpers_2.12-2.6.2.jar;%APP_LIB_DIR%\com.typesafe.play.play-logback_2.12-2.6.2.jar;%APP_LIB_DIR%\ch.qos.logback.logback-classic-1.2.3.jar;%APP_LIB_DIR%\ch.qos.logback.logback-core-1.2.3.jar;%APP_LIB_DIR%\com.typesafe.play.play-akka-http-server_2.12-2.6.2.jar;%APP_LIB_DIR%\com.typesafe.akka.akka-http-core_2.12-10.0.9.jar;%APP_LIB_DIR%\com.typesafe.akka.akka-parsing_2.12-10.0.9.jar;%APP_LIB_DIR%\com.typesafe.play.play-guice_2.12-2.6.2.jar;%APP_LIB_DIR%\com.google.inject.guice-4.1.0.jar;%APP_LIB_DIR%\aopalliance.aopalliance-1.0.jar;%APP_LIB_DIR%\com.google.inject.extensions.guice-assistedinject-4.1.0.jar;%APP_LIB_DIR%\com.h2database.h2-1.4.194.jar;%APP_LIB_DIR%\play-java-starter-example.play-java-starter-example-1.0-SNAPSHOT-assets.jar"
set "APP_MAIN_CLASS=play.core.server.ProdServerStart"
if defined CUSTOM_MAIN_CLASS (
set MAIN_CLASS=!CUSTOM_MAIN_CLASS!
) else (
set MAIN_CLASS=!APP_MAIN_CLASS!
)
rem Call the application and pass all arguments unchanged.
"%_JAVACMD%" !_JAVA_OPTS! !PLAY_JAVA_STARTER_EXAMPLE_OPTS! -cp "%APP_CLASSPATH%" %MAIN_CLASS% !_APP_ARGS!
#endlocal
:end
exit /B %ERRORLEVEL%
I figured it out.
Here are the steps:
I added the plugin play2war in project/plugins.sbt:
addSbtPlugin("com.github.play2war" % "play2-war-plugin" % "1.4.0")
add in build.sbt
import com.github.play2war.plugin._
libraryDependencies ++= Seq( "com.github.play2war" % "play2-war_2.9.1" % "0.8.2" )
Play2WarPlugin.play2WarSettings
Play2WarKeys.servletVersion := "3.1"
execute command sbt war
Except the war generated is quit strange, it contains only jar files, is it normal ?

Rename Files using wildcard paths

Recently I started working and my first task is to write a batch file that automatically changes filenames to filename_date with the original file-ending.
For that you should be able to write paths into a textfile (e.g. paths.txt) and when you start the program, it should take any line (=path->file) from there and rename it.
I got it to work on my PC quiet well but as I gave it to testing they asked to make the use of wildcards Z:\Path\*.* possible.
My current code looks as follows:
#echo off
setlocal EnableDelayedExpansion
cd %~dp0
For /F "tokens=*" %%m in (paths.txt) do (
set path=%%~dpm
set name=%%~nxm
pushd "!path!"
dir
For /r !path! %%f in (!name!) do (
set path=%%~dpf
set name=%%~nf
set ending=%%~xf
set datsave=%%~nxf
set "name=!name!_"
set "name=!name!!date:~6,4!"
set "name=!name!!date:~3,2!"
set "name=!name!!date:~0,2!"
set "name=!name!!ending!"
copy "!datsave!" "!name!"
del "!datsave!"
cls
popd
)
)
I know that a lot of it is probably easier and more efficient to do, but this is my first batch project and I am quiet happy except for the wildcard problem.
So an example would be:
C:\Some\Path\*.*
This line would be in paths.txt.
With the splitting
set path=%%~dpf
set name=%%~nf
set ending=%%~xf
set datsave=%%~nxf
I get the following:
path: C:\Some\Path
name: C:\Some\Path
ending: -empty-
datsave: C:\Some\Path
because name is set to the Path at the start of the first FOR-Loop. But that seems to be working if I do not use wildcards.
Now the question: Why does this happen and how do I get rid of it? Or do I just use the wrong type of wildcards?
Again: This is my first time I work with batch, so it might be something simple ;)
Ok, I figured out 2 problems and now it works
set name=%%~nxm evaluates the wildcard. Even if name is *.txt it will return bar.txt.
I replaced that by a basename computation instead: set name=!name:*\=! done enough times (not very subtle but hey batch files forces us to do such things) which preserves the wildcard
The other problem is the for /R loop: after pushd, the argument needs to be . or it won't be scanned.
Last minor one: use rename instead of copy plus delete. It preserves file time and is very fast. Copying then deleting a large file can take a long time.
#echo off
set DEPTH=20
setlocal EnableDelayedExpansion
cd %~dp0
For /F %%m in (paths.txt) do (
set pth=%%~dpm
set z=%%m
set name=!z!
rem brutal basename. We cannot break the inner loop or
rem it would break the upper loop too
for /L %%I in (1,1,%DEPTH%) do set name=!name:*\=!
rem but we can check if it is really a basename
set chkname=!name:*\=!
if not !chkname!==!name! ( echo please increase DEPTH value
pause
exit /B)
rem set name=%%~nxm
pushd "!pth!"
For /r . %%f in (!name!) do (
set pth=%%~dpf
set name=%%~nf
set ending=%%~xf
set datsave=%%~nxf
set "name=!name!_!date:~6,4!!date:~3,2!!date:~0,2!!ending!
echo renaming "!datsave!" to "!name!"
rem ren "!datsave!" "!name!"
popd
)
)
paths.txt contains just a line C:\full\path\to\test\*.txt
my test directory contains 2 text files and 1 other file
output:
renaming "bar.txt" to "bar_20160812.txt"
renaming "foo.txt" to "foo_20160812.txt"
(just uncomment the ren line to get the job done)
Weeeeell First of all thanks again to #Jean-François Fabre and #aschipfl for their patience with me :)
After the hint with the second batch file I had to test a few things as not everything worked as fine, but now everything works great!
Code of the Main file:
#echo off
setlocal EnableDelayedExpansion
cd %~dp0
set DEPTH=20
For /F %%m in (paths.txt) do (
pause
set pth=%%~dpm
REM pushd !pth!
REM set origpth=!cd!
REM popd
set z=%%m
set name=!z!
For /L %%i in (1,1,%DEPTH%) do set
name=!name:*\=!
set chkname=!name:*\=!
if not !chkname!==!name! ( echo depth to small
pause
exit /B)
rem set name=%%~nxm
pushd "!pth!"
For /r . %%f in (!name!) do (
pushd %~dp0
call renamefiles.bat %%f REM "!origpth!"
popd
)
)
And the code of the sub-file:
#echo off
REM set pth=%~dp1
REM set origpth=%2
REM set origpth=%origpath:"=%\
REM If !pth!==%origpth% (
set path=%~dp1
set name=%~n1
set ending=%~x1
set datsave=%~nx1
pushd !path!
set "name=!name!_!date:~6,4!!date:~3,2!!date:~0,2!!ending!"
pause
echo renaming "!datsave!" to "!name!"
rem "!datsave!" "!name!"
cls
popd
REM )
EDIT: After testing around a bit I figured, that subfolders are included as well! I put extra code to both codes marked with REM and two extra spaces. Take out those REM's and the programm will not longer include subfolders when renaming :)

Resources