Onforum.net - Web and gaming resource community

Register a free account today to become a member! Once signed in, you'll be able to participate on this site by adding your own topics and posts, as well as connect with other members .

Quests /Python MiniTool - Source Server Manager in Python (Building Manager)

Vanilla

Elite
Elite
Credits
1,180
The tool allows you to perform the following actions:
-Compilations:
Compile game / db
Compile game / db with clean
Compile both (consecutively)
Compile both with clean


-Touch (no empty files will be created if you are wrong to write the file name):
Execute the Touch of one or more files in game / src (inserting only the names of the files separated by a space)
Run the Touch of one or more files in db / src (inserting only the names of the files separated by a space)

-Strip:
Stripping game (copying it, keeping the unstripped file)
Stripping db (--same)



Additional features:
- The tool it detects if a file has been modified $ value seconds in the future (if for example you have not correctly set the date of your compilation machine) and will inform you of this, asking even if you want to touchare the file or set the correct date of the machine (or do not do either of the actions ignoring the file)
- The tool if you try to strip a file that does not exist will ask if you need to compile it and (if you choose yes) will start compiling by stripping the file at the end of it.
- The tool is written with procedural python, not object-oriented, it should be easy to customize it if someone wants to do it.
- You can start more than one command in sequence using one of the following characters to divide the command indices: ("&&", "&", "|", "", '\ t', "-", ',') (eg: 1 & 9 -> build game and strip game)
- The tool can also take commandline actions to execute (see below for the list of inputs known to the program) to


know:
- To start a python script on a machine must have installed python (in this case we recommend the 27 just because guaranteed operation). If you do not have it installed you can easily do it with the pkg manager or ports.
- To change the version of python to use with the script you need to change the path to the executable on the first line of the script.
- There should be no changes to the script with any kind of source code, for any problems related to some functionality of the script, you can post it under the discussion and you will be given a solution to the problem.
- To use the script commands, the user you are using is root or has root permissions and permissions are given to the script file as well.
- To start the script you need to position yourself from the shell in the script directory (using the command "cd (call directory)") and then type the command "./nomescript.py"
- If you create the file in which to paste the script from notepad ++ it may be that you set the line terminator characters of windows as an end-of-line character, in this case from "Edit" you can find the entry to change them to "Unix".
- I have tested the file thoroughly for now, I have not found any error, but if you find them you just report them to get the solution to the problem.
- It is possible to disable the question if you want to exit the script or not by simply setting False the constant defined at the beginning of the script.

It is possible to use more than one by separating them from a space.

Code:
--build-game
--build-db
--build-game-clean
--build-db-clean
--build-all
--build-all-clean
--touch-file-gamesrc
--touch-file-dbsrc
--strip-game
--strip-db
--strip-all

Python:
#!/usr/local/bin/python2.7
import os
import time
import sys

ENABLE_ASK_BEFORE_EXIT = True

def get_revision_filename(file):
    if os.path.isfile("__REVISION__"):
        line = open("__REVISION__","r").readline()
        return file + "_r" + line.strip()

    else:
        return file



def check_last_edit(path):
    def check_last_edit_single_file(file):
        nowtime = time.time()
        lastedit = os.path.getmtime(file)
        if nowtime < lastedit:
            ans = ""
            while ans == "":
                print("file [%s] has modified %s seconds in future. do you want to touch it or to change date?\nchoose:(touch/date/n)"%(file , int(lastedit-nowtime)))
                ans = raw_input().strip()
          
                if ans == 'n':
                    break
          
                if ans == 'touch':
                    touch_file("" , file)
          
                elif ans == 'date':
                    print("enter date (YYYYMMDDHHMM):")
                    mydate = raw_input().strip()
              
                    res = os.system("date %s"%mydate)
              
                    if not res in (0,512):
                        print("cannot set datetime. try another option.")
                        ans = ""
                        continue
              
                    nowtime = time.time()
          
                else:
                    print("unknown answer [%s]"%ans)
                    ans = ""

    #end of single file
    if path[-4:] != '/src' and path[-4:] != '\\src':
        path += "/src"

    common = "common"

    files = [path+"/"+file for file in os.listdir(path) if os.path.isfile(path+"/"+file)]
    files += [common+"/"+file for file in os.listdir(common) if os.path.isfile(common+"/"+file)]



    for file in files:
        check_last_edit_single_file(file)


def ask_if_exit():
    if not ENABLE_ASK_BEFORE_EXIT:
        print("exit!")
        sys.exit()


    print("do you want to stop the script operations?y/n\n")

    ans = ""
    while ans == "":
        ans = raw_input().strip()
        if ans == 'y':
            sys.exit()
            return
 
        elif ans == 'n':
            return
 
        else:
            print("unknow answer [%s] , try again"%(ans))
            print("do you want to stop the script operations?y/n\n(press just 'y' or 'n')\n")
            ans = ""


def close():
    print("bye bye")
    sys.exit()

def run_os_command(cmd):
    try:
        res = os.system(cmd)
        if res:
            print("cannot run os command [%s] error %s"%(cmd,str(res)))
            ask_if_exit()
            return False
    except Exception ,e:
        print("an exception during run os command [%s] exception[%s]"%(cmd,str(e)))
        ask_if_exit()
        return False

    return True

def strip_file(file):
    stripfile = file+"_s"
    sourcefile= get_revision_filename(file)

    if not os.path.isfile(file+"/"+sourcefile):
        print("cannot find source file [%s]"%(file+"/"+sourcefile))
        ans=""
 
        while ans == "":
            print("do you want to build it?y/n")
            ans = raw_input().strip()
            if ans == 'y':
                build_file(file)
                strip_file(file)
                return
      
            if ans == 'n':
                return
      
            else:
                print("unknown answer [%s] try again."%ans)
                ans = ""
        return

    if os.path.isfile("%s/%s"%(file,stripfile)):
        os.remove("%s/%s"%(file,stripfile))

    if not run_os_command("cp %s/%s %s/%s"%(file,sourcefile, file , stripfile)):
        return

    run_os_command("strip -s %s/%s"%(file,stripfile))

def strip_db():
    strip_file("db")

def strip_game():
    strip_file("game")

def strip_all():
    strip_db()
    strip_game()

def touch_file(dir , files = ""):
    if len(dir)>0 and dir[-1] != '\\' and dir[-1] != '/':
        dir += "/"

    if files != "":
        files = files.split(" ")
        for file in files:
            if not os.path.isfile(dir+file):
                print("cannot find the file required [%s]."%file)
                continue
      
            else:
                if not run_os_command("touch %s"%(dir + file)):
                    print("cannot find the file required [%s]."%file)
                    continue
          
                else:
                    print("touched %s"%file)
    else:
        print("the path [%s] will automatically added to the file path\nyou can use a space to separate the names to touch more one file"%(dir))
        ans = ""
        while ans == "":
            print("enter the names of the files (exit to exit):")
            ans = raw_input().strip()
      
            if ans == 'exit':
                print("You didn't touch any file.")
                ask_if_exit()
                return
      
            files = ans.split(' ')
      
            for file in files:
                if not os.path.isfile(dir+file):
                    print("cannot find the file required [%s]."%file)
                    if len(files) == 1:
                        ans = ""
                    continue
          
                else:
                    if not run_os_command("touch %s"%(dir + file)):
                        print("cannot find the file required [%s]."%file)
                        if len(files) == 1:
                            ans = ""
                        continue
              
                    else:
                        print("touched %s"%file)


def touch_in_db_src():
    touch_file("db/src")

def touch_in_game_src():
    touch_file("game/src")



def build_all():
    build_game()
    build_db()

def build_all_clean():
    build_game_clean()
    build_db_clean()


def build_file(file):
    check_last_edit(file)
    cmd = "cd %s/src && gmake && cd ../../"%file
    if not run_os_command(cmd):
        return

    output=get_revision_filename("%s/%s"%(file,file))
    if os.path.isfile(output):
        print("build %s successful."%output)

    else:
        print("cannot build file %s."%output)
        ask_if_exit()


def build_game():
    build_file("game")

def build_db():
    build_file("db")


def clean_build(file):
    return run_os_command("cd %s/src && gmake clean && cd ../../"%file) == True


def build_clean(file):
    if not clean_build(file):
        ask_if_exit()

    else:
        print("%s cleaned"%file)

    build_file(file)


def build_db_clean():
    build_clean("db")


def build_game_clean():
    build_clean("game")



EVENTS = {
    1: {
        "name" : "BUILD GAME",
        "event": build_game,
        "cmd" : "--build-game",
    },

    2: {
        "name" : "BUILD DB",
        "event": build_db,
        "cmd" : "--build-db",
    },

    3: {
        "name" : "BUILD GAME CLEAN",
        "event": build_game_clean,
        "cmd" : "--build-game-clean",
    },

    4: {
        "name" : "BUILD DB CLEAN",
        "event": build_db_clean,
        "cmd" : "--build-db-clean",
    },

    5:{
        "name" : "BUILD ALL",
        "event": build_all,
        "cmd" : "--build-all",
    },

    6: {
        "name" : "BUILD ALL CLEAN",
        "event": build_all_clean,
        "cmd" : "--build-all-clean",
    },

    7: {
        "name" : "TOUCH FILE IN game/src",
        "event": touch_in_game_src,
        "cmd" : "--touch-file-gamesrc",
    },

    8: {
        "name" : "TOUCH FILE db/src",
        "event": touch_in_db_src,
        "cmd" : "--touch-file-dbsrc",
    },

    9:{
        "name" : "STRIP GAME",
        "event": strip_game,
        "cmd" : "--strip-game",
    },

    10:{
        "name" : "STRIP DB",
        "event": strip_db,
        "cmd" : "--strip-db",
    },

    11:{
        "name" : "STRIP ALL",
        "event": strip_all,
        "cmd" : "--strip-all",
    },

    0:{
        "name" : "CLOSE",
        "event": close,
        "cmd" : "--close",
    },
}



def print_commandlist():
    print("What do you want to do?\n")
    toprint = [ (EVENTS[key]["name"],str(key)) for key in EVENTS]

    for thing in toprint: print("%s.\t%s"%(thing[1],thing[0]))


def do_cmd(cmd):
    key = int(cmd)
    if not key in EVENTS:
        print("Unknown command [%d] (ignored)\n")
        return

    print("executing [%s]..."%(EVENTS[key]["name"]))
    event = EVENTS[key]["event"]
    event()


def is_right_ans(ans):
    andchar = ("&&","&","|"," ",'\t',"-",',')
    return len([char for char in ans if not char in andchar and not char.isdigit()]) == 0



def do_commands(cmdstr):
    andchar = ("&&","&","|"," ",'\t',"-",',')
    cmdlist = [cmdstr]
    tmp = []

    for char in andchar:
        for cmd in cmdlist:
            tmp = list(cmdlist)
            cmdlist = []
      
            for part in tmp:
                cmdlist+= part.split(char)

    wrong = [cmd for cmd in cmdlist if not cmd.isdigit()]
    if len(wrong) != 0:
        print("found wrong command/commands [%s] (ignored)."%str(wrong))

    for cmd in cmdlist:
        if cmd in wrong:
            continue
 
        do_cmd(cmd)

def main():
    if len(sys.argv) > 1:
        cmdargs = [ (EVENTS[key]["cmd"] , key) for key in EVENTS]
      
        listofargs = [value["cmd"] for value in EVENTS.values()]
        wrongargs = [arg for arg in sys.argv if not arg in listofargs and arg != sys.argv[0]]
      
        if len(wrongargs) != 0:
            print("wrong args [%s] ignored."%(str(wrongargs)))
      
      
        for cmdarg in cmdargs:
            if cmdarg[0] in sys.argv and not cmdarg[0] in wrongargs:
                do_cmd(cmdarg[1])
      
        return
 
 
 
    print_commandlist()

    ans = ""
    while ans == "":
        ans = raw_input().strip()
        if not is_right_ans(ans):
            print("wrong input command.")
            print_commandlist()
            ans = ""
 
    do_commands(ans)





if __name__ == "__main__":
    main()
 
Top

Dear User!

We found that you are blocking the display of ads on our site.

Please add it to the exception list or disable AdBlock.

The advertises that you'll see aren't intrusive they just help us to keep the community alive

If you don't want to see those ads just buy an upgrade.

Thank you for understanding!

Rogue

Rogue Purchase

User upgrade! at

🔥 Upgrade Now
Baba2

Baba2 Purchase

User upgrade! at

🔥 Upgrade Now

Escanor25 Purchase

User upgrade! at

🔥 Upgrade Now