Saving the sketch through code

Hi,

Short question:

Is it possible to script a Processing sketch to make a copy of itself through code?

Reason:

I keep running into an issue where I go back through some images and videos I’ve generated with processing in the past and want to revisit, but inevitably I’ve monkeyed around with the code and I can never quite get back to where I was.

So I try to handle this with careful versioning and manually copying a snapshot of the project each time I generate something I like. But it’s annoying.

I’d like to have the sketch automatically save a copy of its self along side the images I’m rendering in a different location.

Thanks!

1 Like
2 Likes

Hi!

Thanks for the reply. I forgot to mention in my post that Git is what I was referring to with “careful versioning”. But for my workflow it’s still very annoying to have to go through all my commits to find a given version. I tend to fire off 20 or more slight variations for some generative thing, and it’s just really annoying to have to commit each variation to git.

If you go to your GitHub’s repo you may create a new release, which then creates a new branch tag for the current state.

On the repo’s main page, click at “release(s)”, then “Draft a new release”.

For example on this repo of mine:

It’s got 1 branch tag besides “master” named “v1.0.1”:

You can also see that on its “releases” page:

Or “tags”:

You can use those tags to download previous versions, as long as you had created a tag for them.

2 Likes

Yes, you can do this, but notice that you have to actually save the sketch in PDE first. The Processing PDE “run” button copies the active editor window contents and runs that – without saving them to the file. However, a self-saving workaround will access the sketch file contents. If you haven’t saved your sketch, your file contents are out of date, and what you backup is incorrect.

With that caveat, create a tab called “SelfBackup” in any sketch:

import java.util.Date;

void selfBackup() {
  String date = new java.text.SimpleDateFormat("YYYYMMDDHHMMSS").format(new Date().getTime());
  String sketchIn = sketchPath() + '/' + getClass().getName() + ".pde";
  println(sketchIn);
  String sketchOut = sketchPath() + '/' + date + '/' + getClass().getName() + ".pde";
  println(sketchOut);
  copyFile(sketchIn, sketchOut);
}

void copyFile(String sourceFile, String destFile) {
  byte[] source = loadBytes(sourceFile);
  saveBytes(destFile, source);
}

…and then call it from setup:

void setup() {
  selfBackup();
}

Now your sketch creates a backup each time it runs.

Note also that Processing already produces tmp folders on each run. These are transpiled java – not your PDE code – but they can be useful for disaster recovery.

3 Likes

That’s great, thanks for the help!