Simple robust :IsDrive , :IsFolder and :IsFile

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
shodan
Posts: 53
Joined: 01 May 2023 01:49

Simple robust :IsDrive , :IsFolder and :IsFile

#1 Post by shodan » 26 Feb 2024 03:01

Hello,

I needed this function to check if a drive, folder or file existed

Here are the functions, I have also attached full test script I used to test the robustness.

Please let me know if you see flaws

::Usage Call :IsDrive optional OutputVariable a: b: ... n: && IsDrive || IsNotDrive

Code: Select all

::Usage Call :IsDrive optional OutputVariable a: b: ... n: && IsDrive || IsNotDrive
:IsDrive
set "IsDrive_buffer=%~1"
if "[%IsDrive_buffer:~1,1%]" NEQ "[]" if "[%IsDrive_buffer:~1,1%]" NEQ "[:]" ( set "IsDrive_output=%~1" & shift )
:IsDrive-loop
set "IsDrive_drive=%~a1"
if "[%IsDrive_drive:~0,1%]" EQU "[d]" ( set "IsDrive_result=true" ) else ( set "IsDrive_result=false" )
if "[%IsDrive_output%]" NEQ "[]" set "%IsDrive_output%=%IsDrive_result%"
if "[%IsDrive_result%]" EQU "[true]" if "[%~2]" NEQ "[]" ( shift & GoTo :IsDrive-loop )
set "IsDrive_drive=" & set "IsDrive_output=" & set "IsDrive_result=" & if "[%IsDrive_result%]" EQU "[true]" ( exit /b 0 ) else ( exit /b 1 )
Usage Call :IsFolder optional _OutputVar Folder1 Folder2 ... FolderN && IsFolder || IsNotFolder

Code: Select all

::Usage Call :IsFolder optional _OutputVar Folder1 Folder2 ... FolderN && IsFolder || IsNotFolder
:IsFolder
set "IsFolder_buffer=%~1"
if /i "[%IsFolder_buffer:~0,10%]" EQU "[_OutputVar]" ( set "IsFolder_output=%~1" & shift )
:IsFolder-loop
set "IsFolder_drive=%~a1"
if "[%IsFolder_drive:~0,1%]" EQU "[d]" ( set "IsFolder_result=true" ) else ( set "IsFolder_result=false" )
if "[%IsFolder_output%]" NEQ "[]" set "%IsFolder_output%=%IsFolder_result%"
if "[%IsFolder_result%]" EQU "[true]" if "[%~2]" NEQ "[]" ( shift & GoTo :IsFolder-loop )
set "IsFolder_drive=" & set "IsFolder_output=" & set "IsFolder_result=" & if "[%IsFolder_result%]" EQU "[true]" ( exit /b 0 ) else ( exit /b 1 )
Usage Call :IsFile optional _OutputVar File1 File2 ... FileN && IsFile || IsNotFile

Code: Select all

::Usage Call :IsFile optional _OutputVar File1 File2 ... FileN && IsFile || IsNotFile
:IsFile
set "IsFile_buffer=%~1"
if /i "[%IsFile_buffer:~0,10%]" EQU "[_OutputVar]" ( set "IsFile_output=%~1" & shift )
:IsFile-loop
set "IsFile_drive=%~a1"
if "[%IsFile_drive:~0,1%]" EQU "[-]" ( set "IsFile_result=true" ) else ( set "IsFile_result=false" )
if "[%IsFile_output%]" NEQ "[]" set "%IsFile_output%=%IsFile_result%"
if "[%IsFile_result%]" EQU "[true]" if "[%~2]" NEQ "[]" ( shift & GoTo :IsFile-loop )
set "IsFile_drive=" & set "IsFile_output=" & set "IsFile_result=" & if "[%IsFile_result%]" EQU "[true]" ( exit /b 0 ) else ( exit /b 1 )

shodan
Posts: 53
Joined: 01 May 2023 01:49

Re: Simple robust :IsDrive , :IsFolder and :IsFile

#2 Post by shodan » 26 Feb 2024 03:03

Your message contains too few characters.
Attachments
IsFolder.zip
(652 Bytes) Downloaded 61 times
IsFile.zip
(629 Bytes) Downloaded 52 times
IsDrive.zip
(881 Bytes) Downloaded 59 times

shodan
Posts: 53
Joined: 01 May 2023 01:49

Re: Simple robust :IsDrive , :IsFolder and :IsFile

#3 Post by shodan » 27 Feb 2024 17:08

I am trying to create a "template" for publishing finished, ready to use and self-contained functions

I have polished the IsFolder function to as best as I could.

If the file is called IsFolder-demo it will run the internal demo function.
If one of the paramters is /h /? -h -? help --help , it will output the internal help function (doesn't work completely /? also dumps the for and echo /?)

Also I have created a "function card" to describe the function characteristics. This card template is very convenient as you can ask generative AI to fill it for you and it's pretty good.


The function has a basic structure of the following

Code: Select all

@echo off
:setup
:main
GoTo :EOF
Which I think highlight the function driven style I want to have.



Here is the latest version of IsFolder.bat

Code: Select all

@echo off

:setup
:main


for %%a in ( %* ) do ( for %%b in ( /h /? -h -? help --help ) do ( if "[%%a]" EQU "[%%b]" ( Call :%~n0-help & exit /b 1 ) ) )
for %%a in ( %* ) do ( if "[%%a]" EQU "[demo]" ( Call :%~n0-demo & exit /b 1 ) ) 
if "[%~1]" EQU "[]" ( echo %~n0 needs at least one argument & exit /b 1 )
REM if "[%~1]" EQU "[]" if "[%~2]" EQU "[]" ( echo %~n0 needs at least two argument & exit /b 1 )
Call :%~n0 %*


GoTo :EOF


::Usage Call :IsFolder optional _OutputVar Folder1 Folder2 ... FolderN && IsFolder || IsNotFolder
:IsFolder
set "IsFolder_buffer=%~1"
if /i "[%IsFolder_buffer:~0,10%]" EQU "[_OutputVar]" ( set "IsFolder_output=%~1" & shift )
set "IsFolder_buffer="
:IsFolder-loop
set "IsFolder_drive=%~a1"
if "[%IsFolder_drive:~0,1%]" EQU "[d]" ( set "IsFolder_result=true" ) else ( set "IsFolder_result=false" )
if "[%IsFolder_output%]" NEQ "[]" set "%IsFolder_output%=%IsFolder_result%"
if "[%IsFolder_result%]" EQU "[true]" if "[%~2]" NEQ "[]" ( shift & GoTo :IsFolder-loop )
set "IsFolder_drive=" & set "IsFolder_output=" & set "IsFolder_result=" & if "[%IsFolder_result%]" EQU "[true]" ( exit /b 0 ) else ( exit /b 1 )
*******************************************************************************
* Function name : IsFolder                                                    *
* aliases : none                                                              *
*******************************************************************************
* Arguments : (_OutputVar) Folder1 Folder2 ... FolderN                        *
* Return Value : 0 if all folders found, 1 if one of more folder not found    *
* Overloads : none                                                            *
* Creation Date : 2024-02-27 Last Update : 2024-02-27                         *
* Created by : shodan                                                         *
*******************************************************************************
* Version : 1.0                                                               *
* Change History                                                              *
* Date 2024-02-26 : Function created V0.9                                     *
* Date 2024-02-27 : Changed stuff  V1.0                                       *
*******************************************************************************
* Repository : https://www.dostips.com/forum/viewtopic.php?f=3&t=11151        *
* Dependencies : none                                                         *
* Macros : none                                                               *
* Functional state : works                                                    *
* Compatible : Windows 10 22H2                                                *
*******************************************************************************
* Usage Examples                                                              *
*                                                                             *
* To check a single folder existence and print result:                        *
* Call :IsFolder testfolder && echo testfolder is a folder || echo testfolder *
* is not a folder                                                             *
*                                                                             *
* To check multiple folders existence and print result:                       *
* Call :IsFolder testfolder1 testfolder2 && echo Folders exist || echo At     *
* least one folder does not exist                                             *
*                                                                             *
* To use with an output variable:                                             *
* Call :IsFolder _OutputVar_test testfolder1                                  *
* echo Result is %_OutputVar_test%                                            *
*******************************************************************************
* Theory of Operation :                                                       *
* The function iterates through each provided argument (folder path),         *
* checking if it exists and is a directory. If the optional _OutputVar is     *
* specified, the result (true/false) is stored in this variable. If any       *
* folder does not exist or is not a directory, the function returns false.    *
*******************************************************************************
* Function Assumptions :                                                      *
* - The function assumes that all input paths are absolute or relative to the *
* current directory.                                                          *
* - If _OutputVar is used, it must be the first argument.                     *
* - The function stops processing further folders as soon as one does not     *
* exist or is not a directory, optimizing for performance.                    *
*******************************************************************************
* Error handling : none                                                       * 
* Side Effects : none known                                                   *
* Security Considerations : none known                                        * 
* Performance Considerations : none known                                     *
*******************************************************************************
* license : GPL v3                                                            *
* See Also:                                                                   *
*******************************************************************************

:IsFolder-help
echo Usage: IsFolder [OPTIONS] Folder1 [Folder2 ...]
echo Checks if the specified folders exist. Can check multiple folders in one call.
echo.
echo OPTIONS:
echo   _OutputVar    Specifies the variable name to receive the result (true or false).
echo                 This parameter is optional and must be the first argument if used.
echo   FolderX       Specifies the folder(s) to check for existence.
echo.
echo SPECIAL COMMANDS:
echo   /h, /?, -h, -?, help, --help
echo       Display this help message.
echo   demo
echo       Runs the internal demo function to showcase the :IsFolder functionality.
echo.
echo EXAMPLES:
echo   IsFolder _OutputVar testfolder1
echo       Checks if "testfolder1" exists and stores the result in _OutputVar.
echo.
echo   IsFolder testfolder1 testfolder2
echo       Checks if "testfolder1" and "testfolder2" exist.
echo.
echo   IsFolder _OutputVar testfolder1 testfolder2
echo       Checks if "testfolder1" and "testfolder2" exist, storing the result in _OutputVar.
echo.
echo.
goto :EOF



:IsFolder-demo
md testfolder1 2>nul
echo IsFolder test without _outputvar
call :IsFolder _OutputVar_test testfolder0 && echo testfolder0 is a folder || echo testfolder0 is not a folder
call :IsFolder _OutputVar_test testfolder1 && echo testfolder1 is a folder || echo testfolder1 is not a folder
echo two folders
call :IsFolder _OutputVar_test testfolder0 testfolder0 && echo testfolder0 testfolder0 is a folder || echo testfolder0 testfolder0 is not a folder
call :IsFolder _OutputVar_test testfolder1 testfolder1 && echo testfolder1 testfolder1 is a folder || echo testfolder1 testfolder1 is not a folder
call :IsFolder _OutputVar_test testfolder0 testfolder1 && echo testfolder0 testfolder1 is a folder || echo testfolder0 testfolder1 is not a folder
call :IsFolder _OutputVar_test testfolder1 testfolder0 && echo testfolder1 testfolder0 is a folder || echo testfolder1 testfolder0 is not a folder
echo IsFolder test with _outputvar
call :IsFolder _OutputVar_test testfolder0 && echo testfolder0 is a folder || echo testfolder0 is not a folder
echo _OutputVar_test %_OutputVar_test%
call :IsFolder _OutputVar_test testfolder1 && echo testfolder1 is a folder || echo testfolder1 is not a folder
echo _OutputVar_test %_OutputVar_test%
echo two folders
call :IsFolder _OutputVar_test testfolder0 testfolder0 && echo testfolder0 testfolder0 is a folder || echo testfolder0 testfolder0 is not a folder
echo _OutputVar_test %_OutputVar_test%
call :IsFolder _OutputVar_test testfolder1 testfolder1 && echo testfolder1 testfolder1 is a folder || echo testfolder1 testfolder1 is not a folder
echo _OutputVar_test %_OutputVar_test%
call :IsFolder _OutputVar_test testfolder0 testfolder1 && echo testfolder0 testfolder1 is a folder || echo testfolder0 testfolder1 is not a folder
echo _OutputVar_test %_OutputVar_test%
call :IsFolder _OutputVar_test testfolder1 testfolder0 && echo testfolder1 testfolder0 is a folder || echo testfolder1 testfolder0 is not a folder
echo _OutputVar_test %_OutputVar_test%
set "_OutputVar_test="
GoTo :EOF

shodan
Posts: 53
Joined: 01 May 2023 01:49

Re: Simple robust :IsDrive , :IsFolder and :IsFile

#4 Post by shodan » 27 Feb 2024 17:23

As a demonstration of what you can do with generative AI.
Here I have asked it to create the description card for another unrelated function.

Here is the discussion verbatim

I have only omitted the IsFolder card posted above for brevity

-----------chat with chatgpt starts here ------------------

Ok,
Here is the final version of the IsFolder card

-----Isfolder card was pasted here, omitted for brevity--------

I would like you to write the card for the MountVolume function below.

This is the initial publication on 2024-02-27
license is gpl 3
created by shodan
test for Windows 10 22H2
repository viewtopic.php?f=3&t=11???
in a working state

and here is the function

::Usage Call :MountVolume VolumeNumber DriveLetter
:MountVolume
set "_MountVolume_VolumeNumber=%~1"
set "_MountVolume_DriveLetter=%~2"
if "[%_MountVolume_VolumeNumber%]"=="[]" ( echo Missing Volume Number (first parameter^) & exit /b -1 )
if "[%_MountVolume_DriveLetter%]"=="[]" ( echo Missing Drive Letter (second parameter^) & exit /b -1 )
( echo Select Volume %_MountVolume_VolumeNumber% & echo Assign Letter=%_MountVolume_DriveLetter%) | diskpart
set "_MountVolume_VolumeNumber=" & set "_MountVolume_DriveLetter=" & GoTo :EOF

chatgpt classic

Here's the documentation card for the :MountVolume function based on the details you've provided and following the format of the :IsFolder card:

-----------chat with chatgpt ends here ------------------

Code: Select all

*******************************************************************************
* Function name : MountVolume                                                 *
* Aliases : none                                                              *
*******************************************************************************
* Arguments : VolumeNumber, DriveLetter                                       *
* Return Value : 0 if volume is successfully mounted, -1 if an error occurs   *
* Overloads : none                                                            *
* Creation Date : 2024-02-27 Last Update : 2024-02-27                         *
* Created by : shodan                                                         *
*******************************************************************************
* Version : 1.0                                                               *
* Change History                                                              *
* Date 2024-02-27 : Function created V1.0                                     *
*******************************************************************************
* Repository : https://www.dostips.com/forum/viewtopic.php?f=3&t=11???        *
* Dependencies : Requires diskpart utility                                    *
* Macros : none                                                               *
* Functional state : works                                                    *
* Compatible : Windows 10 22H2                                                *
*******************************************************************************
* Usage Examples                                                              *
*                                                                             *
* To mount a volume with volume number 2 as drive Z:                          *
* Call :MountVolume 2 Z                                                       *
*******************************************************************************
* Theory of Operation :                                                       *
* The function uses the diskpart utility to select a volume by its number     *
* and assign it a new drive letter. It requires two parameters: the volume    *
* number and the drive letter to assign. If any parameter is missing, the     *
* function displays an error message and exits with a return code of -1.      *
*******************************************************************************
* Function Assumptions :                                                      *
* - The function assumes diskpart utility is available and functional on the  *
*   system.                                                                   *
* - User has administrative privileges required to run diskpart commands.     *
*******************************************************************************
* Error handling :                                                            *
* - Checks for missing Volume Number or Drive Letter and exits with -1 if any *
*   are missing.                                                              *
* Side Effects : Changes the system's volume mount configuration              *
* Security Considerations : Running diskpart requires administrative          *
*   privileges and can impact system configuration.                           *
* Performance Considerations : The execution time is dependent on system      *
*   performance and diskpart utility speed.                                   *
*******************************************************************************
* License : GPL v3                                                            *
* See Also:                                                                   *
*******************************************************************************
This card provides a comprehensive overview of the :MountVolume function, including its purpose, usage, and important considerations. Make sure to replace the placeholder in the repository URL (viewtopic.php?f=3&t=11???) with the actual thread ID where the function is discussed or published.

USER

Please note possible bugs or sensible improvements to this functions.
Also is there more information that should be communicated to the user and programmer that use this function ?

Here is the current output of this function

MountVolume.bat 4 A

Microsoft DiskPart version 10.0.19041.3636

Copyright (C) Microsoft Corporation.
On computer: SHODAN

DISKPART>
Volume 4 is the selected volume.

DISKPART>
DiskPart successfully assigned the drive letter or mount point.

DISKPART>

CHATGPT classic

The :MountVolume function you've provided is a practical tool for mounting volumes with a new drive letter using the diskpart utility in Windows. However, like any script, it may have areas where improvements or additional error checks could enhance its robustness, usability, and safety. Here are some possible improvements and additional information that could be beneficial for users and programmers:
Possible Improvements

Error Handling Enhancement:
The script assumes diskpart executes successfully. However, diskpart operations can fail due to various reasons (e.g., permissions, invalid volume number, or the drive letter is already in use). Capturing diskpart's success or failure and reflecting it in the script's exit code or output could be valuable.
Consider checking the output of the diskpart command for specific error messages or success indicators to provide more detailed feedback to the user.

Input Validation:
Validate the Volume Number to ensure it's a positive integer.
Validate the Drive Letter to ensure it's a single letter followed optionally by :. Additionally, check if the drive letter is already in use to prevent accidental overrides.

Automated Privilege Check:
Since diskpart requires administrative privileges, adding a check at the beginning of the script to ensure it's running with the necessary privileges can prevent confusing errors for the user.

Safety and Confirmation:
Adding a confirmation prompt before executing potentially disruptive operations like changing drive letters could prevent accidental system changes, especially in scripts that might be run in automated scenarios.

Additional Information for Users and Programmers

Backup and Recovery:
Emphasize the importance of having backups before making system changes. Though changing a drive letter is generally safe, unexpected issues can arise.

Impact on System and Applications:
Note that changing a drive letter can affect applications or services that rely on specific paths. Users should be aware of the potential need to update configurations after making changes.

Administrative Requirements:
Clearly state that the script requires administrative privileges to run successfully.

Compatibility Notes:
If there are any specific Windows versions or configurations where the script is known to have issues, these should be documented.

Use Cases:
Provide examples of practical use cases for the function, helping users understand when and why they might want to use it.

Related Functions:
If you have other related scripts or functions (for example, unmounting volumes, listing available volumes, etc.), mentioning these and how they relate could be useful for users looking to perform related tasks.

Incorporating these improvements and additional pieces of information into the function's documentation and logic can significantly enhance its utility, safety, and user-friendliness. Adjusting the script to handle errors gracefully, validate inputs thoroughly, and ensure that it's run with appropriate privileges will make it more robust and reliable for a wide range of use cases.

USER

please write the function :MountVolume-help

CHATGPT classic

To provide comprehensive help documentation for the :MountVolume function, you can create a :MountVolume-help subfunction within your batch file. This help function will detail usage instructions, parameters, requirements, and other important information to guide users and programmers. Below is an example of how the :MountVolume-help function could be written:

Code: Select all

:MountVolume-help
echo *******************************************************************************
echo * Function name : MountVolume
echo * Description   : Assigns a new drive letter to the specified volume.
echo *******************************************************************************
echo * Usage: %~n0 VolumeNumber DriveLetter
echo * Example: %~n0 4 Z
echo *    This example assigns drive letter Z to volume number 4.
echo *******************************************************************************
echo * Parameters:
echo *   VolumeNumber - The numeric identifier of the volume to be mounted.
echo *   DriveLetter  - The drive letter to assign to the volume. Must be a single
echo *                 letter from A to Z. The colon (:) after the letter is optional.
echo *******************************************************************************
echo * Return Value:
echo *   0 - If the volume is successfully mounted with the new drive letter.
echo *   -1 - If there is an error due to missing parameters or diskpart failure.
echo *******************************************************************************
echo * Requirements:
echo *   - Requires administrative privileges to run successfully.
echo *   - diskpart utility must be available on the system.
echo *******************************************************************************
echo * Notes:
echo *   - Changing a drive letter can impact applications relying on specific paths.
echo *   - Ensure the new drive letter is not already in use to prevent conflicts.
echo *   - Use with caution and verify volume numbers and drive letters carefully.
echo *******************************************************************************
echo * Error Handling:
echo *   - The function checks for missing parameters and reports if either the
echo *     VolumeNumber or DriveLetter is not provided.
echo *   - It does not perform error checking on the execution success of diskpart.
echo *******************************************************************************
echo * See Also:
echo *   - For related functions and further documentation, visit:
echo *     https://www.dostips.com/forum/viewtopic.php?f=3&t=11???
echo *******************************************************************************
echo * License: GPL v3
echo *******************************************************************************
goto :EOF
To use this help function, you would typically invoke it when the user provides a help-related argument (such as /?, help, etc.) or when incorrect parameters are supplied. This can be done by adding a condition at the beginning of your script to check for these cases and then call :MountVolume-help accordingly.

This help subfunction aims to be both informative and user-friendly, providing clear guidance on how the :MountVolume function should be used, what to expect from it, and important considerations to keep in mind. Adjust the URL in the "See Also" section to match the actual location where your function or related discussions are hosted.



---------


You can view the full discussion that created this output at
https://chat.openai.com/share/9141db76- ... 4bfc4a2a42

I post because, the answers of chatgpt are affected by the rest of the whole context.

shodan
Posts: 53
Joined: 01 May 2023 01:49

Re: Simple robust :IsDrive , :IsFolder and :IsFile

#5 Post by shodan » 27 Feb 2024 17:56

Now I have attempted this type of documentation with chatgpt but starting from a fresh context.
Here are the results, you should be easily able to reproduce this for your functions with minimal efforts

You only have to paste your self-contained function and answer the questionnaire.

The questionnaire

Code: Select all

This is the initial publication date of publication 2024-??-??
version is 0.?
license is YOURLICENSEHERE
created by YOURUSERNAME
test for YOURWINDOWSVERSION
repository https://www.dostips.com/forum/viewtopic.php?f=3&t=YOURPOSTHERE
function is in a FUNCTIONSTATEHER state
The function to be documented

Code: Select all

::Usage Call :DecompressFile Filename
:DecompressFile
set "_Decompress_File=%~1"
set "_Decompress_Filename=%~n1"
set "_Decompress_Filepath=%~dp1"
if "[%_Decompress_Filepath:~0,-1%]" EQU "[\]" set "_Decompress_Filepath=%_Decompress_Filepath:~0,-1%"
set "_Decompress_ExtraFiles="
for /f "tokens=*" %%a in ('tar -tf "%_Decompress_File%" --exclude "%_Decompress_Filename%"') do ( set "_Decompress_ExtraFiles=true" )
if "[%_Decompress_ExtraFiles%]" EQU "[true]" md "%_Decompress_Filepath%%_Decompress_Filename%" 2>nul
if "[%_Decompress_ExtraFiles%]" EQU "[true]" tar -xf "%_Decompress_File%" -C "%_Decompress_Filepath%%_Decompress_Filename%"
if "[%_Decompress_Filepath:~-1%]" EQU "[\]" set "_Decompress_Filepath=%_Decompress_Filepath:~0,-1%"
if "[%_Decompress_ExtraFiles%]" NEQ "[true]" tar -xf "%_Decompress_File%" -C "%_Decompress_Filepath%"
if "[%~2]" NEQ "[]" ( shift & GoTo :DecompressFile )
set "_Decompress_File=" & set "_Decompress_Filename=" & set "_Decompress_ExtraFiles="
GoTo :EOF
----------------------------------------------The discussion ----------------------------------------------
https://chat.openai.com/share/11988a46- ... fa9efd4252

-------------USER-------------

Please fill out the this function card template, using the instructions found below, for the function provided at the end of this message.



Code: Select all

*******************************************************************************
* Function name : <FunctionName>
* Aliases : <AnyAliases>
*******************************************************************************
* Description : <BriefDescriptionOfWhatTheFunctionDoes>
*******************************************************************************
* Parameters :
*   <ParameterName> : <DataType> - <Description> (Default: <DefaultValue>)
*******************************************************************************
* Return Value : <DescribeReturnValueAndMeaning>
* Overloads : <ListAnyOverloadsIfApplicable>
*******************************************************************************
* Creation Date : <DateCreated> Last Update : <LastUpdatedDate>
* Created by : <AuthorName>
*******************************************************************************
* Version : <VersionNumber>
* Change History :
*   Date <YYYY-MM-DD> : <ChangeDescription> V<VersionNumber>
*******************************************************************************
* Repository : <URLToCodeRepositoryOrDocumentation>
* Dependencies : <AnyDependenciesTheFunctionHas>
* Configuration Files: <PathsAndDescriptionsOfConfigurationFiles>
* Environment Variables: <ListAndDescribeEnvironmentVariables>
*******************************************************************************
* Functional state : <CurrentStateOfWorkingOrNot>
* Compatible : <CompatibilityInformation>
* Test Coverage: <DescriptionOfTestCoverage>
*******************************************************************************
* Usage Examples :
*   <Example1>
*   <Example2>
*******************************************************************************
* Theory of Operation :
*   <DetailedDescriptionOfHowTheFunctionWorksInternally>
*******************************************************************************
* Function Assumptions :
*   <AnyAssumptionsMadeByTheFunction>
*******************************************************************************
* Error handling :
*   <HowErrorsAreHandled>
* Side Effects :
*   <AnySideEffectsOfUsingTheFunction>
* Security Considerations :
*   <AnySecurityRisksOrConsiderations>
* Performance Considerations :
*   <AnyPerformanceImpactsOrConsiderations>
*******************************************************************************
* Internationalization and Localization: <SupportDetails>
* Accessibility: <AccessibilityFeaturesOrConsiderations>
* Thread Safety: <ThreadSafetyInformation>
* Memory Management: <MemoryManagementDetails>
*******************************************************************************
* Related Tools and Libraries: <RelatedResources>
* See Also :
*   <RelatedFunctionsOrDocumentation>
*******************************************************************************
* FAQs:
*   <FrequentlyAskedQuestionsAndAnswers>
*******************************************************************************
* User Feedback: <HowUsersCanProvideFeedbackOrReportBugs>
* Contact Information: <AuthorOrMaintainerContactInfo>
*******************************************************************************
* Ethical Considerations: <EthicalUseAndPotentialMisuse>
* License : <LicenseUnderWhichTheFunctionIsReleased>
*******************************************************************************
* Examples Repository: <LinkToExamples>
*******************************************************************************



Instructions for Documenting Functions Using the Function Card Template

To ensure comprehensive documentation of a function, follow these guidelines when filling out the function card template. This template is designed to provide a detailed overview of a function's purpose, usage, and other critical information. Tailor the documentation to fit the function's complexity, the environment it operates in, and its intended audience.
Basic Information

Function Name and Aliases: Specify the unique name of the function and any aliases it may have.
Description: Provide a brief summary of the function's purpose and what it accomplishes.
Creation Date / Last Update: Include the dates when the function was initially created and most recently updated.
Created by: Note the name of the function's author or primary maintainer.
Version / Change History: Document the current version and maintain a log of significant changes over time.

Technical Details

Parameters and Return Value:
Parameters: List each parameter the function accepts, including the expected data types, a brief description, and default values if applicable.
Return Value: Describe what the function returns and the significance of the return value(s).
Overloads: If the function supports overloading, detail the alternative signatures here.
Repository: Provide a link to the code repository or documentation for the function.
Dependencies: List any external scripts, libraries, or tools the function depends on.

Operational Context

Functional State: Indicate whether the function is experimental, stable, deprecated, etc.
Compatibility: Include compatibility information, such as supported operating systems or environments.
Environment Variables: Document any environment variables that affect the function's operation.
Configuration Files: If applicable, specify paths to relevant configuration files and describe their contents.
Thread Safety: State whether the function is thread-safe and under what conditions.
Memory Management: Discuss considerations for memory allocation and deallocation, especially for languages with manual memory management.

Usage and Best Practices

Usage Examples: Provide concrete examples showing how to use the function effectively.
Theory of Operation: Offer a detailed explanation of how the function works internally, if relevant.
Function Assumptions: List any assumptions or preconditions for the function's use.
Error Handling: Explain how the function handles errors or exceptional conditions.
Side Effects: Note any unintended effects of using the function.
Security, Performance, and Ethical Considerations: Address potential security implications, performance impacts, and ethical concerns related to the function's use.

Additional Information

Internationalization and Localization: Mention support for different languages, regions, or cultural norms.
Accessibility: Note any features or considerations related to accessibility.
Test Coverage: Provide details on the extent of test coverage.
Examples Repository: If available, link to a repository of examples demonstrating the function's use.
FAQs: Include frequently asked questions and answers about the function.
User Feedback: Offer methods for users to provide feedback or report bugs.
Related Tools and Libraries: List resources that complement the function or are commonly used with it.
Contact Information: Provide contact details for further inquiries or support.
License: Document the license under which the function is released.

Customization and Updates

Adjust the level of detail and technical language to match your audience's needs.
Regularly review and update the function card to reflect any changes in the function's design, usage, or operational context.

This comprehensive approach ensures that the function card serves as a valuable resource for users and developers, providing not only technical details but also broader contextual information that aids in responsible and effective use.



The function to be documented

Code: Select all

::Usage Call :DecompressFile Filename
:DecompressFile
set "_Decompress_File=%~1"
set "_Decompress_Filename=%~n1"
set "_Decompress_Filepath=%~dp1"
if "[%_Decompress_Filepath:~0,-1%]" EQU "[\]" set "_Decompress_Filepath=%_Decompress_Filepath:~0,-1%"
set "_Decompress_ExtraFiles="
for /f "tokens=*" %%a in ('tar -tf "%_Decompress_File%" --exclude "%_Decompress_Filename%"') do ( set "_Decompress_ExtraFiles=true" )
if "[%_Decompress_ExtraFiles%]" EQU "[true]" md "%_Decompress_Filepath%%_Decompress_Filename%" 2>nul
if "[%_Decompress_ExtraFiles%]" EQU "[true]" tar -xf "%_Decompress_File%" -C "%_Decompress_Filepath%%_Decompress_Filename%"
if "[%_Decompress_Filepath:~-1%]" EQU "[\]" set "_Decompress_Filepath=%_Decompress_Filepath:~0,-1%"
if "[%_Decompress_ExtraFiles%]" NEQ "[true]" tar -xf "%_Decompress_File%" -C "%_Decompress_Filepath%"
if "[%~2]" NEQ "[]" ( shift & GoTo :DecompressFile )
set "_Decompress_File=" & set "_Decompress_Filename=" & set "_Decompress_ExtraFiles="
GoTo :EOF
Answers to questions that cannot be answered by the code

This is the initial publication
date of publication 2024-02-27
version is 0.9
license is gpl 3
created by shodan
test for Windows 10 22H2
repository viewtopic.php?f=3&t=11???
function is in a working state

-------------CHATGPTCLASSIC-------------

Code: Select all

*******************************************************************************
* Function name : DecompressFile
* Aliases : None
*******************************************************************************
* Description : Decompresses a specified file using the 'tar' command, handling 
*               both single and multiple file archives by extracting them into 
*               their respective directories.
*******************************************************************************
* Parameters :
*   Filename : String - The name of the file to be decompressed.
*******************************************************************************
* Return Value : None
* Overloads : None
*******************************************************************************
* Creation Date : 2024-02-27 Last Update : 2024-02-27
* Created by : shodan
*******************************************************************************
* Version : 0.9
* Change History :
*   Date 2024-02-27 : Initial publication V0.9
*******************************************************************************
* Repository : https://www.dostips.com/forum/viewtopic.php?f=3&t=11???
* Dependencies : Requires the 'tar' command-line utility.
* Configuration Files: None
* Environment Variables: None
*******************************************************************************
* Functional state : Working
* Compatible : Tested on Windows 10 version 22H2
* Test Coverage: Basic functionality tested with single and multiple file archives.
*******************************************************************************
* Usage Examples :
*   DecompressFile archive.tar.gz
*   DecompressFile package.tar
*******************************************************************************
* Theory of Operation :
*   The function first determines the full path, name, and directory of the file 
*   to be decompressed. It checks for extra files within the archive. If extra 
*   files are present, it creates a directory named after the file and extracts 
*   all contents into this directory. If no extra files are found, it extracts 
*   the contents into the current directory. The function supports decompression 
*   of both types of tar archives (with or without extra files) by utilizing 
*   conditional logic and the 'tar' utility.
*******************************************************************************
* Function Assumptions :
*   - The 'tar' utility is available and functional in the command line environment.
*   - The file to be decompressed is a tar archive.
*******************************************************************************
* Error handling :
*   Errors from the 'tar' command are redirected to null, and the function does 
*   not explicitly handle errors. Users should verify successful decompression.
* Side Effects :
*   May create a new directory for the decompressed files.
* Security Considerations :
*   Ensure that the source of the tar archives is trusted, as decompressing files 
*   can potentially extract harmful content.
* Performance Considerations :
*   Decompression time and performance depend on the size of the archive and the 
*   speed of the host system.
*******************************************************************************
* Internationalization and Localization: Not applicable
* Accessibility: Not applicable
* Thread Safety: Not thread-safe due to potential concurrent write operations 
*                to the same directory or files.
* Memory Management: Not applicable, relies on the 'tar' utility for file operations.
*******************************************************************************
* Related Tools and Libraries: tar command-line utility
* See Also :
*   tar(1) - manual page for the tar command
*******************************************************************************
* FAQs:
*   Q: Can it decompress other types of archives?
*   A: No, it is specifically designed for tar archives.
*******************************************************************************
* User Feedback: For feedback or bug reports, please visit the forum thread at 
*                the repository URL.
* Contact Information: Not provided
*******************************************************************************
* Ethical Considerations: Use responsibly when decompressing files from 
*                         untrusted sources.
* License : GPL 3
*******************************************************************************
* Examples Repository: Not available
*******************************************************************************
-------------USER-------------

Please fill out the this help function template, using the instructions found below, for the function described above

:function-help
echo *******************************************************************************
echo * Function Name: <FunctionName>
echo * Description: <BriefDescriptionOfWhatTheFunctionDoes>
echo *******************************************************************************
echo * Usage:
echo * <FunctionName> <Parameter1> <Parameter2> ... <ParameterN>
echo *
echo * Parameters:
echo * <Parameter1> - <DescriptionOfParameter1>
echo * <Parameter2> - <DescriptionOfParameter2>
echo * ...
echo * <ParameterN> - <DescriptionOfParameterN>
echo *
echo * Options:
echo * <Option1> - <DescriptionOfOption1>
echo * <Option2> - <DescriptionOfOption2>
echo * ...
echo * <OptionN> - <DescriptionOfOptionN>
echo *******************************************************************************
echo * Examples:
echo * 1. <ExampleUsage1>
echo * <ExampleDescription1>
echo *
echo * 2. <ExampleUsage2>
echo * <ExampleDescription2>
echo *
echo * ...
echo *
echo * N. <ExampleUsageN>
echo * <ExampleDescriptionN>
echo *******************************************************************************
echo * Additional Notes:
echo * <AnyAdditionalInformationOrNotesRelatedToTheFunction>
echo *******************************************************************************
echo * See Also:
echo * - <RelatedFunctionOrDocumentation1>
echo * - <RelatedFunctionOrDocumentation2>
echo * ...
echo * - <RelatedFunctionOrDocumentationN>
echo *******************************************************************************
goto :EOF


Instructions for Writing a Function-Help Function

Creating a function-help function is essential for providing users with guidance on how to use your command-line tools effectively. The template you've provided is a solid foundation. Here's how to enrich it with detailed, user-friendly help documentation.
Basic Structure

Your function-help should follow the provided template closely, enhancing clarity and completeness with each section.
Detailed Instructions
Function Name and Description

Function Name: Replace <FunctionName> with the exact name of the function.
Description: Fill in <BriefDescriptionOfWhatTheFunctionDoes> with a concise yet comprehensive description of the function's purpose and what it accomplishes.

Usage

Command Structure: Clearly outline how to invoke the function, including its name and the sequence of parameters and options. Replace <FunctionName>, <Parameter1>, <Parameter2>, ..., <ParameterN> with the actual names and order of use.
Parameters and Options: Detail each parameter and option the function accepts.
For Parameters, list each one with a brief description, indicating optional parameters if applicable.
For Options, list each supported option (like /?, /h, -h, -?, help, --help) and describe what it does. Include any additional options your function supports with a clear description of their effects.

Examples

Practical Examples: Provide real-world examples of how to use the function. Include common use cases, demonstrating the function with various parameters and options. This section is crucial for helping users understand practical applications of the function.
Description: For each example, include a brief description explaining what the example does. This helps users grasp the purpose and outcome of each command sequence.

Additional Notes

Further Information: Use this section to mention any additional details users should be aware of. This could include notes on execution environment, dependencies, potential side effects, or any limitations of the function.

See Also

Related Resources: List any related functions, documentation, or external resources that might help the user. This is a great way to guide users towards more comprehensive understanding or advanced usage.

Best Practices

Clarity and Conciseness: Ensure all explanations are clear and to the point. Avoid jargon and overly technical language unless your target audience is familiar with such terms.
Organization: Keep the help content well-organized, following the template structure to ensure users can easily find the information they need.
Accessibility: Consider the varied expertise levels of your audience. Provide enough detail for beginners while still being useful for more advanced users.
Regular Updates: As your function evolves, regularly update the help documentation to reflect new options, changed functionality, or deprecated features.

Implementation Tips

Implement command-line parsing at the beginning of your function to detect help-related options (/?, /h, -h, -?, help, --help). Upon detecting any of these options, the function should immediately display the help content and exit.
Test the help function thoroughly to ensure it displays correctly across different terminals and handles edge cases gracefully.
Consider adding a version option (-v, --version) to your function-help output, providing users with quick access to the function's current version.

By following these instructions and utilizing the template, you will create a function-help that enhances user experience, fostering a better understanding and more effective use of your function.

-------------CHATGPTCLASSIC-------------

Code: Select all

:function-help
echo *******************************************************************************
echo * Function Name: DecompressFile
echo * Description: Decompresses a specified file using the 'tar' command, handling 
echo *               both single and multiple file archives by extracting them into 
echo *               their respective directories.
echo *******************************************************************************
echo * Usage:
echo *   DecompressFile Filename
echo *
echo * Parameters:
echo *   Filename - The name of the file to be decompressed. This is a required parameter.
echo *
echo * Options:
echo *   There are no options for this function. It strictly requires a filename as input.
echo *******************************************************************************
echo * Examples:
echo *   1. DecompressFile archive.tar.gz
echo *      This example decompresses the 'archive.tar.gz' file into the current directory or into a 
echo *      new directory named after the archive if it contains multiple files.
echo *
echo *   2. DecompressFile package.tar
echo *      This example decompresses the 'package.tar' archive, extracting its contents into the 
echo *      current directory or a new directory if the archive contains multiple items.
echo *******************************************************************************
echo * Additional Notes:
echo *   - Ensure that the 'tar' utility is available in your command line environment before using 
echo *     this function.
echo *   - The function is designed to work on Windows 10 version 22H2 and might not be compatible 
echo *     with other versions or operating systems without modification.
echo *   - Errors during decompression are not explicitly handled by this function and should be 
echo *     manually checked.
echo *******************************************************************************
echo * See Also:
echo *   - tar(1) - manual page for the tar command
echo *******************************************************************************
goto :EOF

shodan
Posts: 53
Joined: 01 May 2023 01:49

Re: Simple robust :IsDrive , :IsFolder and :IsFile

#6 Post by shodan » 27 Feb 2024 17:59

And here is the result function so far

DecompressFile.zip
(2.26 KiB) Downloaded 59 times

Code: Select all

@echo off

:setup
:main

for %%a in ( %* ) do ( for %%b in ( /h /? -h -? help --help ) do ( if "[%%a]" EQU "[%%b]" ( Call :%~n0-help & exit /b 1 ) ) )
for %%a in ( %* ) do ( if "[%%a]" EQU "[demo]" ( Call :%~n0-demo & exit /b 1 ) ) 
if "[%~1]" EQU "[]" ( echo %~n0 needs at least one argument & exit /b 1 )
REM if "[%~1]" EQU "[]" if "[%~2]" EQU "[]" ( echo %~n0 needs at least two argument & exit /b 1 )
Call :%~n0 %*


GoTo :EOF

::Usage Call :DecompressFile Filename
:DecompressFile
set "_Decompress_File=%~1"
set "_Decompress_Filename=%~n1"
set "_Decompress_Filepath=%~dp1"
if "[%_Decompress_Filepath:~0,-1%]" EQU "[\]" set "_Decompress_Filepath=%_Decompress_Filepath:~0,-1%"
set "_Decompress_ExtraFiles="
for /f "tokens=*" %%a in ('tar -tf "%_Decompress_File%" --exclude "%_Decompress_Filename%"') do ( set "_Decompress_ExtraFiles=true" )
if "[%_Decompress_ExtraFiles%]" EQU "[true]" md "%_Decompress_Filepath%%_Decompress_Filename%" 2>nul
if "[%_Decompress_ExtraFiles%]" EQU "[true]" tar -xf "%_Decompress_File%" -C "%_Decompress_Filepath%%_Decompress_Filename%"
if "[%_Decompress_Filepath:~-1%]" EQU "[\]" set "_Decompress_Filepath=%_Decompress_Filepath:~0,-1%"
if "[%_Decompress_ExtraFiles%]" NEQ "[true]" tar -xf "%_Decompress_File%" -C "%_Decompress_Filepath%"
if "[%~2]" NEQ "[]" ( shift & GoTo :DecompressFile )
set "_Decompress_File=" & set "_Decompress_Filename=" & set "_Decompress_ExtraFiles="
GoTo :EOF
*******************************************************************************
* Function name : DecompressFile
* Aliases : None
*******************************************************************************
* Description : Decompresses a specified file using the 'tar' command, handling 
*               both single and multiple file archives by extracting them into 
*               their respective directories.
*******************************************************************************
* Parameters :
*   Filename : String - The name of the file to be decompressed.
*******************************************************************************
* Return Value : None
* Overloads : None
*******************************************************************************
* Creation Date : 2024-02-27 Last Update : 2024-02-27
* Created by : shodan
*******************************************************************************
* Version : 0.9
* Change History :
*   Date 2024-02-27 : Initial publication V0.9
*******************************************************************************
* Repository : https://www.dostips.com/forum/viewtopic.php?f=3&t=11???
* Dependencies : Requires the 'tar' command-line utility.
* Configuration Files: None
* Environment Variables: None
*******************************************************************************
* Functional state : Working
* Compatible : Tested on Windows 10 version 22H2
* Test Coverage: Basic functionality tested with single and multiple file archives.
*******************************************************************************
* Usage Examples :
*   DecompressFile archive.tar.gz
*   DecompressFile package.tar
*******************************************************************************
* Theory of Operation :
*   The function first determines the full path, name, and directory of the file 
*   to be decompressed. It checks for extra files within the archive. If extra 
*   files are present, it creates a directory named after the file and extracts 
*   all contents into this directory. If no extra files are found, it extracts 
*   the contents into the current directory. The function supports decompression 
*   of both types of tar archives (with or without extra files) by utilizing 
*   conditional logic and the 'tar' utility.
*******************************************************************************
* Function Assumptions :
*   - The 'tar' utility is available and functional in the command line environment.
*   - The file to be decompressed is a tar archive.
*******************************************************************************
* Error handling :
*   Errors from the 'tar' command are redirected to null, and the function does 
*   not explicitly handle errors. Users should verify successful decompression.
* Side Effects :
*   May create a new directory for the decompressed files.
* Security Considerations :
*   Ensure that the source of the tar archives is trusted, as decompressing files 
*   can potentially extract harmful content.
* Performance Considerations :
*   Decompression time and performance depend on the size of the archive and the 
*   speed of the host system.
*******************************************************************************
* Internationalization and Localization: Not applicable
* Accessibility: Not applicable
* Thread Safety: Not thread-safe due to potential concurrent write operations 
*                to the same directory or files.
* Memory Management: Not applicable, relies on the 'tar' utility for file operations.
*******************************************************************************
* Related Tools and Libraries: tar command-line utility
* See Also :
*   tar(1) - manual page for the tar command
*******************************************************************************
* FAQs:
*   Q: Can it decompress other types of archives?
*   A: No, it is specifically designed for tar archives.
*******************************************************************************
* User Feedback: For feedback or bug reports, please visit the forum thread at 
*                the repository URL.
* Contact Information: Not provided
*******************************************************************************
* Ethical Considerations: Use responsibly when decompressing files from 
*                         untrusted sources.
* License : GPL 3
*******************************************************************************
* Examples Repository: Not available
*******************************************************************************


:function-help
echo *******************************************************************************
echo * Function Name: DecompressFile
echo * Description: Decompresses a specified file using the 'tar' command, handling 
echo *               both single and multiple file archives by extracting them into 
echo *               their respective directories.
echo *******************************************************************************
echo * Usage:
echo *   DecompressFile Filename
echo *
echo * Parameters:
echo *   Filename - The name of the file to be decompressed. This is a required parameter.
echo *
echo * Options:
echo *   There are no options for this function. It strictly requires a filename as input.
echo *******************************************************************************
echo * Examples:
echo *   1. DecompressFile archive.tar.gz
echo *      This example decompresses the 'archive.tar.gz' file into the current directory or into a 
echo *      new directory named after the archive if it contains multiple files.
echo *
echo *   2. DecompressFile package.tar
echo *      This example decompresses the 'package.tar' archive, extracting its contents into the 
echo *      current directory or a new directory if the archive contains multiple items.
echo *******************************************************************************
echo * Additional Notes:
echo *   - Ensure that the 'tar' utility is available in your command line environment before using 
echo *     this function.
echo *   - The function is designed to work on Windows 10 version 22H2 and might not be compatible 
echo *     with other versions or operating systems without modification.
echo *   - Errors during decompression are not explicitly handled by this function and should be 
echo *     manually checked.
echo *******************************************************************************
echo * See Also:
echo *   - tar(1) - manual page for the tar command
echo *******************************************************************************
goto :EOF

shodan
Posts: 53
Joined: 01 May 2023 01:49

Re: Simple robust :IsDrive , :IsFolder and :IsFile

#7 Post by shodan » 27 Feb 2024 18:12

And if you read, you can see that there are errors !
This is the catch of this method.
While it is very quick to get a draft there are errors.

You will have to proofread it, you can ask chatgpt to proofread it and it will probably find some errors.

But you really should read it all at least once. You already didn't have to write it so that still a MAJOR time saving.
(except compared with not documenting your functions lol !)

Here are the errors I found

Code: Select all

:function-help
The help function is not named correctly, it should be called :DecompressFile-help

Code: Select all

* Function Assumptions :
*   - The file to be decompressed is a tar archive.
This is not true, I wrote and tested this function to unpack .zip files. This is the tar that comes with windows 10.

Code: Select all

* Aliases : None
Not the AI fault, but I want to add UncompressFile as an alias and I didn't tell it

Code: Select all

* Test Coverage: Basic functionality tested with single and multiple file archives.
I tested with single archives, I'm not sure it works with multiple archives, but it might ...

Code: Select all

* Usage Examples :
*   DecompressFile archive.tar.gz
*   DecompressFile package.tar
I did not test tar files or even .gz files .... might work

It got the Theory of Operation right, NICE !

Code: Select all

* Side Effects :
*   May create a new directory for the decompressed files.
lol, but true

Code: Select all

* Thread Safety: Not thread-safe due to potential concurrent write operations 
*                to the same directory or files.
Not sure it would apply .... I'm not a good enough programmer to know about thread safe batch files

Code: Select all

* FAQs:
*   Q: Can it decompress other types of archives?
*   A: No, it is specifically designed for tar archives.
Pure lies, it does zip at least.

It also does ISO **** However, the ISO I just tried, is a hybrid ISO9660 plus UDF, so it only unpacked the ISO9660 and not the UDF part, oh well !

Code: Select all

D:\shodan\Desktop\rEFInd installation with dark mode>DecompressFile.bat Win10_22H2_EnglishInternational_x64.iso

cd Win10_22H2_EnglishInternational_x64

D:\shodan\Desktop\rEFInd installation with dark mode\Win10_22H2_EnglishInternational_x64>dir
 Volume in drive D has no label.
 Volume Serial Number is 14E9-25D3

 Directory of D:\shodan\Desktop\rEFInd installation with dark mode\Win10_22H2_EnglishInternational_x64

2024-02-27  19:09    <DIR>          .
2024-02-27  19:09    <DIR>          ..
2022-09-08  19:00               135 README.TXT
               1 File(s)            135 bytes
               2 Dir(s)  24,646,508,544 bytes free

That's about it for now !

Post Reply