AmarokStudios

Include Full Directory

1 post in this topic

Good afternoon AutoIt community!,

I was on Stackoverflow the other day and came across this question: How To Include Files From A Directory. This got me thinking... There has to be a way to do it... After a bunch of research, I wasn't able to find anything. So, I created this UDF to dynamically include every file from the directory. Of course, there are some bugs that I'd like to fix eventually, but for the most part, it works. Simply call the main function (Shown below) right after the rest of the includes before any of your actual code, and the UDF will include all of the au3 files in the specified directory. Without further ado, here is the _includeDir UDF and how to use it!

 

_includeDir.au3

Spoiler
#cs
        Name: _includeDir.au3
        Developer: Timothy Bomer
        Copyright: Amarok Studios LLC 2016
        Version: 1.0
        Description:
            The purpose of this UDF is to dynamically include all files inside of a folder.
            It works for the most part, but I am still working on a couple of bugs.
#CE


#Include <File.au3>


Global $mainUDF = "IncludeDirUDF"
Global $includeLib = $mainUDF & "\" & "loadIncludes.au3"
Global $tempLib = $mainUDF & "\" & "lib.txt"
Global $includeRewrite = $mainUDF & "\rewrite.au3"
Global $iDirHolder = ""


Func _includeDir($iDir, $lineToInc = 1, $restart = True)
    If (checkInclude()) = 1 Then
        FileDelete($tempLib)
        return
    EndIf
    If NOT (FileExists($iDir)) Then
        MsgBox(16,"Directory Doesn't Exists | _includeDir","The directory " & $iDir & " does not exist!")
        return 0
    EndIf
    $iDirHolder = $iDir
    initializeCheck()
    ; MsgBox(0,"Include Directory", "Attempting to include: " & $iDir)
    populateLib($iDir)
    populateIncLib()
    finalize($lineToInc, $restart)
EndFunc

Func checkInclude()
    FileOpen(@ScriptName, 0)
    For $i = 1 to _FileCountLines(@ScriptName)
        $checkLine = FileReadLine(@ScriptName, $i)
        If ($checkLine = '#Include "IncludeDirUDF\loadIncludes.au3"') Then
        return 1
        EndIf
    Next
EndFunc

; START Initialize Check
Func initializeCheck()
    ; MsgBox(0,"Checking. . .", "Is this initialized?")
    If (FileExists($mainUDF)) Then
        If NOT (FileExists($includeLib)) Then
            isError(2)
            return
        EndIf

        ; MsgBox(0,"Initialized","The UDF has been initialized")
    Else
        isError(1)
        return
    EndIf
EndFunc
; END Initialize Check

; START Library Population
Func populateLib($iDir = $iDirHolder)
    ; MsgBox(0,"Populating","Attempting to populate the library")
    If (FileExists($tempLib)) Then
        ; MsgBox(0,"Temp File Found","The temporary library file has been found. Attempting to populate.")
        $tLibCont = _FileListToArray(@ScriptDir & "\" & $iDir & "\", "*")
        $iDirSize = $tLibCont[0]
        ; MsgBox(0,"Size of Included Directory", $iDir & " contains " & $iDirSize & " files to include!")
        $writeLib = FileOpen($tempLib, 1)
        While $iDirSize > 0
            FileWriteLine($writeLib, '#Include "..\' & $iDir & '\' & $tLibCont[$iDirSize] & '"')
            $iDirSize -= 1
        WEnd
        FileClose($writeLib)
    Else
        isError(3)
        return
    EndIf
EndFunc
; END Library Population

; START Include Library Population
Func populateIncLib()
    ; MsgBox(0,"Rewriting. . .", "Attempting to re-write the include library")
    #CS
    If (FileExists($includeLib)) Then
        FileDelete($includeLib)
        _FileCreate($includeLib)
    EndIf
    #CE
    FileOpen($tempLib, 0)
    For $i = 1 to _FileCountLines($tempLib)
        $line = FileReadLine($tempLib, $i)
        $reWriteLib = FileOpen($includeLib, 9)
        FileWriteLine($reWriteLib, $line)
        FileClose($reWriteLib)
    Next
    FileClose($tempLib)
EndFunc
; END Include Library Population

; START Finalize
Func finalize($lineToInc, $restart)
    _FileWriteToLine(@ScriptName, $lineToInc, '#Include "IncludeDirUDF\loadIncludes.au3"', False)
    If ($restart = True) Then
        runFile(@ScriptName)
    EndIf
    exit
    return
EndFunc


Func runFile($rFile)
    $file_loc = $rFile

    If @Compiled = 1 Then
         $file_exe = FileGetShortName(@AutoItExe & ' /AutoIt3ExecuteScript "' & $file_loc & '"')
         Run($file_exe)
    Else
         $file_au3 = FileGetShortName($file_loc)
         Run(@AutoItExe & " " & $file_au3, "", @SW_HIDE)
     EndIf
EndFunc

; START Error Reporting
Func isError($eFlag = "", $eMessage = "There was an error!")
    If ($eFlag = "") Then
        ; MsgBox(16,"ERROR", $eMessage)
        Exit
    EndIf

    If ($eFlag = 1) Then
        ; MsgBox(16,"Not Initialized","This UDF has not been initialized")
        DirCreate($mainUDF)
        Sleep(250)
        initializeCheck()
        return
    ElseIf ($eFlag = 2) Then
        ; MsgBox(16,"Missing File","Missing the include library!")
        _FileCreate($includeLib)
        initializeCheck()
        return

    ElseIf ($eFlag = 3) Then
        ; MsgBox(16,"Missing File", "Missing the temporary library! Creating it now!",3)
        _FileCreate($tempLib)
        populateLib()
        return
    EndIf
EndFunc
; END Error Reporting

 

 

Download this code (_includeDir.au3 attached as well) and place it into the directory with your current script. Next, include it in your main file. For now, I'm going to be using one called Example.au3.

 

#Include "_includeDir.au3"

Now, include whatever else you're going to be including in this script, then call the _includeDir function. NOTE: THIS MUST BE CALLED AT THE TOP OF THE SCRIPT, BEFORE ANY CODE IS WRITTEN! THE FUNCTION FORCES THE SCRIPT TO RESTART SO PUTTING IT LATER IN THE SCRIPT WILL RE-RUN THE CODE!

 

Example.au3

#Include "_includeDir.au3"
#Include <File.au3> ; Not needed. Just here as an example of a normal script.
#Include <Array.au3> ; Not needed. Just here as example of normal script.
_includeDir("Directory to Include")

MsgBox(0,"Example","This is just an example!")

See how the function is called near the top? This is the proper use of the UDF. If you had a folder called "Directory to Include" and had a bunch of .au3 files inside of it, the function would include them all into the Example.au3 script.

If you run the Example.au3 file now, it will most likely tell you "The directory Things to Include does not exist!". Make sure you enter the name of the directory you're trying to include. Just as a side note, when including files, you should put all of the code in the INCLUDED files inside of functions so they aren't automatically run when included. Variables can be outside of the functions so they are automatically set. Remember, if you have a variable in one included file with the same name of variable in another included file, it will be overwritten with whichever include file was included last.

 

Anyways, if you have pointed the directory to include parameter to a folder that exists and run the Example.au3, it will generate a folder called IncludeDirUDF. It will also write a new line inside of Example.au3. It will write the line 

Quote

#Include "IncludeDirUDF\loadIncludes.au3"

on line one. Of course, you don't always want it to be written to line one, right? Maybe you want this bit of code to be written on line 3 in order to keep your code organize. Is there a way to do this? Absolutely! Simply add the line number as a second parameter to the function. For example, we want to have this bit of code written on line 3, we would set up our Example.au3 file to look like this.

#Include "_includeDir.au3"
#Include <File.au3> ; Not needed. Just here as an example of a normal script.
#Include <Array.au3> ; Not needed. Just here as example of normal script.
_includeDir("Directory to Include", 3)

MsgBox(0,"Example","This is just an example!")

See how we added the 3 to the end of _includeDir? This will tell the function to write the #Include "IncludeDirUDF\loadIncludes.au3" on line 3 of Example.au3. Note, the line HAS TO EXIST in order to be written to it. For example, if your Example.au3 code only has 6 lines, and you specify to be written on line 7, it WILL NOT WORK.

 

The code is designed to include and restart in order to process the included files. For some reason, if you want to JUST generate the included file and NOT restart, you can add one more parameter to the code. If you don't want the code to restart, simply set your code up to look like this:

#Include "_includeDir.au3"
#Include <File.au3> ; Not needed. Just here as an example of a normal script.
#Include <Array.au3> ; Not needed. Just here as example of normal script.
_includeDir("Directory to Include", 3, False)

MsgBox(0,"Example","This is just an example!")

Note, if you set this last parameter to false, it will simply generate the included file and write to line 3 of Example.au3 (As specified before) and exit before the code reaches the MsgBox() and it will not be displayed.

 

The last important thing to note: In order to re-include a different set of files, you must delete the #Include "IncludeDirUDF\loadIncludes.au3" from your main script (In this case, Example.au3) and delete the generated file, IncludeDirUDF. Now you can simply rerun Example.au3 and it will include any the dir with any changes you made to it. Only .au3 files should be in the directory you're trying to include as it will not process the other files and will generate an error.

 

I hope this UDF helps somebody out! Comment any questions/concerns you may have and I will try to address them as soon as possible!

 

Thanks,

Timothy

CEO - Amarok Studios

_includeDir.au3

Share this post


Link to post
Share on other sites



Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now

  • Similar Content

    • Skysnake
      By Skysnake
      Scite comes up occasional, almost incidentally, in some support topics.  I have not found a "Scite" topic in the forums, so this is where I will start.  I have recently been using Scite intensively, specifically with a large project and I have certain issues.  I know that Scite is not an AutoIt product, but it is so closely integrated to the core release that it makes sense to raise issues and request support here.  If this is not the right please refer me to the right forum.
      Thx
       
      Skysnake
    • P3rsp3ctiv3
      By P3rsp3ctiv3
      Hello how can I send a {Enter} into the edit window ($cmd)? I tried it first with:
      GUICtrlSetData($cmd, "Line 1" + "{ENTER}")
      but it doesn´t work. Can someone help me please?
      #include <ButtonConstants.au3> #include <EditConstants.au3> #include <GUIConstantsEx.au3> #include <StaticConstants.au3> #include <WindowsConstants.au3> #include <GUIConstants.au3> $Admin = GUICreate("Admin", 234, 168, 192, 229, $GUI_SS_DEFAULT_GUI, BitOR($WS_EX_OVERLAPPEDWINDOW,$WS_EX_TRANSPARENT,$WS_EX_WINDOWEDGE)) GUISetBkColor(0xB4B4B4) $exit = GUICtrlCreateButton("Close", 160, 136, 65, 25) $cmd = GUICtrlCreateEdit("",0, 0, 225, 137, $ES_AUTOVSCROLL + $WS_VSCROLL) GUICtrlSetData(-1, "") GUICtrlSetFont(-1, 10, 400, 0, "Candara") GUICtrlSetBkColor(-1, 0xE3E3E3) $cmd_clear = GUICtrlCreateButton("Clear", 9, 136, 65, 25) GUISetState(@SW_SHOW) HotKeySet("{f1}", CMD_1) HotKeySet("{f2}", CMD_2) While 1 $msg = GUIGetMsg(1) Switch $msg[0] Case $GUI_EVENT_CLOSE Exit Case $exit GUIDelete($Admin) Exit EndSwitch WEnd Func CMD_1(); GUICtrlSetData($cmd, "Line 1" & "{ENTER}") GUICtrlSetData($cmd, "Line 2" & "{ENTER}") EndFunc Func CMD_2(); GUICtrlSetData($cmd, "Line 3" & "{ENTER}") GUICtrlSetData($cmd, "Line 4" & "{ENTER}") EndFunc
    • nacerbaaziz
      By nacerbaaziz
      hello
      please i need to link a progress bar with a time can you help me?
      e.g
      i want to set a progress bar for 10 sec
      am waiting for your answers
      thank you.
    • AdminC
      By AdminC
      #RequireAdmin
      #include <SendMessage.au3>
      #include <WinAPI.au3>
      #include <WindowsConstants.au3>
      #include <GDIPlus.au3>
      #include <GUIConstantsEx.au3>
      #include <WinAPIGdi.au3>
      #include <Array.au3>
      #include <WinAPIDiag.au3>
      $Imglocation = @ScriptDir&"\Image\testimg.bmp"
      _GDIPlus_Startup()
      Local $Bitmap = _GDIPlus_BitmapCreateFromFile($Imglocation)
      Local $hBitmap = _GDIPlus_BitmapCreateHBITMAPFromBitmap($Bitmap)
      Local $imgSize = _WinAPI_GetBitmapDimension($hBitmap)
      Local $imgBits = DllStructCreate('dword[' & ($imgSize.X * $imgSize.Y) & ']')
      _WinAPI_GetBitmapBits($hBitmap, DllStructGetSize($imgBits), DllStructGetPtr($imgBits))
      _WinAPI_DisplayStruct($imgBits)
      MsgBox(0, "", DllStructGetData($imgBits, 1, 1)) 
      _GDIPlus_Shutdown()
      DllstructGetData can't get data color B, G, R value. Who's know that? teach me plz
       
    • Miliardsto
      By Miliardsto
      Hello. Im trying to make my scripts safe - unnable to decompile. I search for obfuscators and other security methods but the search has come to nothing.
      Then one guy gave that idea below. If I rightly understood this idea lets we talk about example program with this secutiy method.
      Program have two parts, first is only login gui and the second part is the main program Second part (main program) is uploaded on ftp server lets say that on http://xxx/autoit/main_program.au3 So we have the first gui with login, we put correctly login and pass and this is the moment when code from http://xxx/autoit/main_program.au3 will be downloaded and executed Finally main program will be appear This is the similiar way like new games are protected by cracking.
      I have few questions in this moment about this:
      Is something like that even possible to do with the autoit? First part of program (login gui) must have somewhere given that link to download the rest of code - http://xxx/autoit/main_program.au3 to make it execute. As we know this first part of program is easy able to hack and retrieve this web url http://xxx/autoit/main_program.au3 where located is main part of program. Is the way to encrypt or secure it? If only code will be stored in .php we know it cannot be previewed. So it could for example get code from .php file instead of .au3 I know that methods works in other languages (I dont know exactly how) thats becouse I only speculates, maybe something may looks different in these solution? Other way would be compiling second part of code on web server (there are available web autoit servers) maybe this way is possible? Tell me anything U know about this ideas and if its even possible to achieve.
      Thanks for ur any response, advice or thoughts