This is a sample script for modifying the revisions of a file on Google Drive using Google Apps Script. This script can be used for not only Google Docs files, but also the files except for Google Docs.
Issue and workaround:
Unfortunately, in the current stage, at Google Docs files, the revision of Google Docs cannot be directly changed by APIs with a script. So as one of several workarounds, I would like to propose to overwrite the Google Docs file using the exported data. On the other hand, at the files except for Google Docs, the data can be directly retrieved with the revision ID. This can be used for overwriting the file. The flow of this script is as follows.
For Google Docs files:
- Retrieve the exported endpoint from the Google Docs file with the revision ID.
- In this case, the Google Docs file is exported as the Microsoft Docs file.
- Retrieve the blob from the exported endpoint.
- Overwrite the Google Docs with the retrieved blob.
For files except for Google Docs:
- Retrieve the blob with the file ID and revision ID.
- Overwrite the file with the retrieved blob.
By this flow, all files can be reverted to the previous version.
IMPORTANT:
As an important point, when the Google Docs file is exported as the Microsoft Docs file, at the most cases, the overwritten Google Docs files are not changed from the original Google Docs for the version. But I’m not sure that this workaround works perfectly for all cases. So please be careful this.
Sample script:
The sample script is as follows. Before you run the script, please enable Drive API at Advanced Google services. And also, please set the variables of revisionId
and fileId
. revisionId
can be retrieved by the method of Revisions: list of Drive API.
function revertRevision() {
var revisionId = "###"; // Please set the revision ID you want to revert.
var fileId = "###"; // Please set the file ID.
var endpoint = "";
var token = ScriptApp.getOAuthToken();
var res = Drive.Revisions.get(fileId, revisionId);
if (res.mimeType.indexOf("application/vnd.google-apps") > -1) {
var endpoints = res.exportLinks;
var keys = Object.keys(endpoints);
for (var i = 0; i < keys.length; i++) {
if (
keys[i].indexOf("application/vnd.openxmlformats-officedocument") > -1
) {
endpoint = endpoints[keys[i]] + "&access_token=" + token;
break;
}
}
} else {
endpoint =
"https://www.googleapis.com/drive/v3/files/" +
fileId +
"/revisions/" +
revisionId +
"?alt=media&access_token=" +
token;
}
var mediaData = UrlFetchApp.fetch(endpoint).getBlob();
Drive.Files.update({}, fileId, mediaData);
}
Note:
- If you want to revert perfectly to the previous version for Google Docs file, in the current stage, I recommend to manually revert.
References:
- Advanced Google services
- Revisions: get
- Files: update
- How to revert back document to a previous revision