iTranslated by AI
How to Retrieve Your Own Project Files in Google Apps Script
Hello, I'm luth.
I'm a non-programmer who entered the world of programming through GAS and went on to study Vue/React and TypeScript. I've been developing internal tools for my team for about four years.
While developing within the team, we faced the following challenges:
- There are no developers in the team proficient enough to handle Node.js.
- GitHub cannot be used due to internal rules (since we are not a development department).
- Some DriveAPI features (including GAS's DriveApp) have domain-level restrictions.
- Due to the above, there was no way to maintain script backups or update histories other than manual copying.
While searching for a way forward, I came up with a brute-force method to address these issues: "Fetch your own/other GAS projects from a GAS project and manage them using a Git-like approach in a Spreadsheet"...! (A bit aggressive, I know.)
I haven't seen any other articles specifically about the "fetching your own/other GAS projects from a GAS project" part, so I'll summarize it here.
The implementation of the Spreadsheet management part depends on individual skill levels and team literacy, so it is outside the scope of this article.
Code to fetch your own or other GAS projects from a GAS project
/**
* [For type definition only; do not use outside of JSDoc] Type definition for the retrieved project file data.
* @type {{ projectName: string, scriptId: string, files: { id: string, name: string, type: 'json'|'gs'|'html', source: string }[] }}
*/
const ProjectFileType_ = undefined;
/**
* [Constant for adding permissions; do not use] Constant definition solely to inform GAS that 'DriveApp OAuth permission is required!'.
*/
const _drive_ = DriveApp.getStorageUsed;
/**
*
* @param {string} scriptId Script ID. If fetching from the project itself, obtain it with `ScriptApp.getScriptId()`, etc.
* @param {string} accessToken Access token. Obtain it with `ScriptApp.getOAuthToken()` from an account that has access rights to the target project.
* @returns {ProjectFileType_ || {}} `ProjectFileType_.files[].source` is the source code within each file.
*/
function getScriptFiles(scriptId, accessToken) {
const downloadUrl = `https://script.google.com/feeds/download/export?id=${scriptId}&format=json`;
let projectName;
try {
const res = UrlFetchApp.fetch(downloadUrl, {
method: 'get',
headers: {
authorization: 'Bearer ' + accessToken,
muteHttpExceptions: true
}
});
const responseCode = res.getResponseCode();
const responseHeaders = res.getHeaders();
if (responseCode !== 200 || responseHeaders['Content-Type'] !== 'application/json') throw Error(res.getContentText());
json = res.getContentText();
json = JSON.parse(json);
json.files = json.files.map(file => {
file.type = file.type === 'server_js' ? 'gs' : file.type;
file.name = `${file.name}.${file.type}`;
return file;
});
projectName = (
responseHeaders['Content-Disposition']
.match(/filename\*=UTF\-8''(.+)\.json/i)
|| [, null]
)[1];
projectName = decodeURI(projectName);
} catch (e) {
console.error(e.stack);
return {};
}
return {
projectName,
scriptId,
files: json.files
}
}
Example of fetching the script: The execution file itself
function getOwnScript() {
const scriptId = ScriptApp.getScriptId();
const accessToken = ScriptApp.getOAuthToken();
const { files } = getScriptFiles(scriptId, accessToken);
if (!files) throw Error('Failed to retrieve script files');
files.forEach(({ name, source }) => {
console.log({ name });
console.log(source);
});
}
Example of fetching the script: Managing multiple other files
function getOtherScripts() {
const scriptIds = [
'abcde01234fghijkl56789',
'abcde01234fghijkl56780',
'abcde01234fghijkl56781',
]
const accessToken = ScriptApp.getOAuthToken();
scriptIds.forEach(scriptId => {
const { projectName, files } = getScriptFiles(scriptId, accessToken);
if (!files) throw Error('Failed to retrieve script files');
files.forEach(({ name, source }) => {
console.log({ projectName, fileName: name });
console.log(source);
});
});
}
Use Cases
- Write to a spreadsheet or similar to use as a backup or for tracking edit history.
- Reference diff libraries to identify differences between versions.
- Corrected
scriptFiles.gsbecausefile.typewas different from the design.
Discussion