Skip to content

Instantly share code, notes, and snippets.

@CuboidRaptor
Created July 15, 2023 23:17
Show Gist options
  • Select an option

  • Save CuboidRaptor/5f9f074aabf140a666acb7889c5facd2 to your computer and use it in GitHub Desktop.

Select an option

Save CuboidRaptor/5f9f074aabf140a666acb7889c5facd2 to your computer and use it in GitHub Desktop.
stupid batch wrapper that wraps yoru scripts into an exe for convienience
# imports...?
import argparse
import os
import tempfile
import random
import time
import subprocess
import shutil
class FileNameError(Exception):
pass
def procpath(pth, slashcompat=True, dbackslash=False):
# shitty windows paths
if slashcompat:
# linux *happy noises*
pth = pth.replace("\\", "/").replace("//", "/")
else:
# windows *fiery hell noises*
pth = pth.replace("/", "\\").replace("\\\\", "\\")
if dbackslash:
# *silence*
pth=pth.replace("\\", "\\\\")
return pth
# amazing args
parser = argparse.ArgumentParser(
description="convert .bats idfk figure it out"
)
parser.add_argument(
"file",
metavar="file",
type=str,
help="file (oh wow amazing I didn't know that)"
)
args = parser.parse_args()
args.file = procpath(os.path.abspath(args.file))
# chdir because I'm lazy
os.chdir(procpath(os.path.dirname(args.file)))
oldwd = os.getcwd() # I have to change back later
# temp dir so I can write dumb shat to it
tdir = procpath(os.path.abspath(tempfile.gettempdir()))
llist = list("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")
# read script
with open(procpath(os.path.basename(args.file)), "r") as f:
data = f.read().split("\n")
while True:
# generate rando poopy head until no conflicts
try:
tfdump = f"{tdir}/b2e_Temp_{round(time.time())}_{''.join([random.choice(llist) for i in range(0, 32)])}"
os.mkdir(tfdump)
break
except FileExistsError:
# conflicts, regenerate
continue
os.chdir(tfdump) # I got lazy again whoops
# open new c++ script in file name
cname = ".".join(procpath(os.path.basename(args.file)).split(".")[:~0])
if len(cname) == 0:
raise FileNameError("Name without extensions returned as empty")
with open(f"{cname}.cpp", "w") as f:
# generate
cppstr = []
for i in data:
temp = i.replace('\\', '\\\\').replace('"', '\\"')
cppstr.append(temp)
cppstr = f"\"" + "\\n".join(cppstr) + "\""
f.write("""// This C++ script was generated by Cuboid's Bat2Exe service.
// includes
#include <string>
#include <fileapi.h>
#include <iostream>
#include <fstream>
#include <random>
#include <chrono>
#include <windows.h>
#include <vector>
int main(int argc, char *argv[])
{
// hardcoded script
std::string runscript = """ + cppstr + """;
std::string tdir;
char tdir_ch[MAX_PATH]; // get temp dir
GetTempPathA(MAX_PATH, tdir_ch);
tdir = tdir_ch;
// generate random temp folder name
std::string llist = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
// time, which is hard for some reason
const auto p1 = std::chrono::system_clock::now();
int timestamp = std::chrono::duration_cast<std::chrono::seconds>(p1.time_since_epoch()).count();
std::string fname = tdir + "\\\\b2e_App_" + std::to_string(timestamp) + "_"; // i'm alternating between competence and rolling on the floor laughing
for (int i = 0; i < 32; i++)
{
// rng, which is harder
std::random_device gen;
std::uniform_int_distribution<std::random_device::result_type> dist(0, 61); // im legit crying
std::string ch; // generating randomized temp script name
char ch_ch = llist[dist(gen)];
ch = ch_ch;
fname += ch;
}
fname += ".bat";
std::ofstream out(fname.c_str()); // writing script
out << runscript;
out.close();
std::string all_args; // Add args
std::vector<std::string> arg_list(argv + 1, argv + argc);
for (const auto &piece: arg_list)
{
all_args += std::string{*" "} + piece;
}
std::string fname2 = fname + all_args;
// aaaand execute
STARTUPINFO info={sizeof(info)};
PROCESS_INFORMATION processInfo;
if (CreateProcess(NULL, &fname2[0], NULL, NULL, TRUE, 0, NULL, NULL, &info, &processInfo))
{
WaitForSingleObject(processInfo.hProcess, INFINITE);
CloseHandle(processInfo.hProcess);
CloseHandle(processInfo.hThread);
}
remove(fname.c_str());
}""")
os.chdir(oldwd) # change back so no winerror when removing temp folder
subprocess.call(f"g++ {tfdump}/{cname}.cpp -o {oldwd}/{cname}.exe") # compile omgomg
shutil.rmtree(tfdump) # remove dumb temp folder that no one likes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment