Search code examples
perforcep4python

p4python create and submit a new file


How to create and submit a new file using p4python?

create_and_submit_file(full_path_in_depot, new_file_text_content):
    logging.basicConfig(level=logging.INFO, format=LOG_FORMAT)
    p4 = get_p4() # implemented
    try:  # Catch exceptions with try/except
        connect_and_login_p4(p4) # implemented

        # .. implementation here .. p4.some_call() 

        LOGGER.info('done')
    except P4Exception:
        for e in p4.errors:  # Display errors
            LOGGER.error(e)

Solution

  • If the file already exists on the local filesystem within a workspace, all you need to do is p4.run_add(file) and p4.run_submit('-d', 'this is my awesome file').

    If the file doesn't exist, you need to create it, and if you don't have a workspace, you need to create that too. For the sake of brevity, here's how you'd do that from the command line completely from scratch (this maps pretty directly to P4Python but I don't know enough about your environment to give you code that'll work out of the box so I won't attempt the translation):

    echo "my awesome file content" > my_awesome_file
    p4 set P4CLIENT=my_awesome_client
    p4 --field "View=//depot/... //my_awesome_client/..." client -o | p4 client -i
    p4 add my_awesome_file
    p4 submit -d "this is my awesome file"
    

    Check out the example for p4.save_client to see a simple example of how you can create/modify a client spec with P4Python and modify the fields to suit your environment (similar to how I used the --field flag to set the View such that the root of my_awesome_client corresponds to //depot/...):

    https://www.perforce.com/perforce/r14.2/manuals/p4script/python.p4.html#python.p4.save_spectype