pythonperforce

How to check file content in a python script being run in a perforce trigger?


Goal:
I am trying to run checks against files users want to submit to validate them and block submission of bad files

Docs:
I am referencing https://www.perforce.com/manuals/p4sag/Content/P4SAG/scripting.triggers.submits.content.html which says

The following change-content trigger is a Bourne shell script that ensures that every file in every changelist contains a copyright notice for the current year.

And goes

  # p4 print -q //depot/src/file.c@=12345

My Code:
My perforce trigger table entry looks something like

check_hydra_json_trigger change-submit //foo/... "C:\Python38\python.exe %//foo/script.py% %changelist%"

My script.py file looks like

changelist_number = sys.argv[1]
change = p4.run_describe(changelist_number)
file_list = change[0]['depotFile']

for file_path in file_list:
    if file_path.endswith('.json'):         
        output = p4.run("print", "-o", temp_file, f"{file_path}@{changelist_number}")
    
        data = None
        try:
            with open(temp_file, "r") as temp_file_contents:
                data = json.load(temp_file_contents)
        except Exception as e:
            print(f"Error: Failed to load json {file_path}. Is file properly formatted?")
            print(f"Exception: {e}")

My issue is temp_file always contains the contents of the depot file, not the file that we're trying to submit.

No luck having change-content as my trigger instead...


Solution

  • Change this line:

    output = p4.run("print", "-o", temp_file, f"{file_path}@{changelist_number}")
    

    to:

    output = p4.run("print", "-o", temp_file, f"{file_path}@={changelist_number}")
    

    and make sure that your trigger is running as change-content rather than change-submit.

    The important detail is the @= revision specifier, which can be used to refer to unsubmitted files on the server (i.e. a midflight submit in a change-content trigger, or a shelved change -- note that at the time change-submit fires, the files are not yet on the server).

    Normally a revision specifier can only ever refer to submitted revisions, but @= is a special exception when it refers to a pending change that contains either mid-submit or shelved files.