Skip to content

Commit

Permalink
Added Clean up Dry Runs Script
Browse files Browse the repository at this point in the history
  • Loading branch information
YashTotale committed Feb 9, 2021
1 parent 374fdda commit a49878c
Show file tree
Hide file tree
Showing 10 changed files with 215 additions and 69 deletions.
38 changes: 28 additions & 10 deletions .eslintignore
Original file line number Diff line number Diff line change
@@ -1,15 +1,33 @@
# dependencies
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*

# Dependency directories
node_modules/

# testing
coverage/
# Optional npm cache directory
.npm

# production
dist/
out/
build/
# Optional eslint cache
.eslintcache

# misc
serviceaccount.json
# dotenv environment variables file
.env
remind-template.html
.env.test

# Outputs
out/
output/

# Secrets
credentials.json
oauth-token.json
.clasprc.json

# Misc
.DS_Store
remind-mail.html
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ out/
output/

# Secrets
serviceaccount.json
credentials.json
oauth-token.json
.clasprc.json

# Misc
Expand Down
10 changes: 3 additions & 7 deletions .markdownlintignore
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
# dependencies
# Dependency directories
node_modules/

# testing
coverage/

# production
dist/
# Outputs
out/
build/
output/
36 changes: 27 additions & 9 deletions .prettierignore
Original file line number Diff line number Diff line change
@@ -1,15 +1,33 @@
# dependencies
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*

# Dependency directories
node_modules/

# testing
coverage/
# Optional npm cache directory
.npm

# production
dist/
out/
build/
# Optional eslint cache
.eslintcache

# misc
serviceaccount.json
# dotenv environment variables file
.env
.env.test

# Outputs
out/
output/

# Secrets
credentials.json
oauth-token.json
.clasprc.json

# Misc
.DS_Store
remind-mail.html
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,8 @@
"postinstall": "replace-in-file \"declare var console\" \"//declare var console\" node_modules/@types/google-apps-script/google-apps-script.base.d.ts",
"contributors:add": "all-contributors add",
"contributors:generate": "all-contributors generate",
"contributors:check": "all-contributors check"
"contributors:check": "all-contributors check",
"clean-up-dry-runs": "ts-node scripts/clean-up-dry-runs.ts"
},
"dependencies": {
"airtable": "^0.10.1",
Expand Down
148 changes: 148 additions & 0 deletions scripts/clean-up-dry-runs.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
// Externalss
import { readFile, writeFile } from "fs/promises";
import { join } from "path";
import { promisify } from "util";
import readline, { createInterface } from "readline";
import { google, Auth, drive_v3 } from "googleapis";
import moment from "moment";

// Internals
import keyfile from "../credentials.json";
import Logger from "../src/Helpers/Logger";

readline.Interface.prototype.question[promisify.custom] = function (
prompt: string
) {
return new Promise((resolve) =>
readline.Interface.prototype.question.call(this, prompt, resolve)
);
};

// @ts-expect-error Defining new method
readline.Interface.prototype.questionAsync = promisify(
readline.Interface.prototype.question
);

const TOKEN_PATH = join(__dirname, "..", "oauth-token.json");

const cleanUpDryRuns = async () => {
const oAuth2Client = new google.auth.OAuth2(
keyfile.installed.client_id,
keyfile.installed.client_secret,
keyfile.installed.redirect_uris[0]
);

await authorize(oAuth2Client);

const drive = google.drive({
version: "v3",
auth: oAuth2Client,
});

const dryRunsFolder = await getAllDryRuns(drive);

for (const item of dryRunsFolder.files ?? []) {
Logger.line();
const id = item.id ?? "";

const fileData = await getDryRunData(drive, id);

Logger.bold(fileData.name ?? "");

const shouldDelete = shouldDeleteFile(fileData);

if (shouldDelete) deleteFile(drive, id);
else {
Logger.success(
`This file is not stale! (modified less than 1 month ago)`
);
}
}
};

const authorize = async (
oAuth2Client: Auth.OAuth2Client
): Promise<Auth.Credentials> => {
Logger.log("Authorizing...");
let token: Auth.Credentials;
try {
const rawToken = await readFile(TOKEN_PATH, "utf-8");
token = JSON.parse(rawToken);
oAuth2Client.setCredentials(token);
} catch (e) {
const authUrl = oAuth2Client.generateAuthUrl({
access_type: "offline",
scope: ["https://www.googleapis.com/auth/drive"],
});

Logger.line();
Logger.log(`Authorize this app by visiting this url: ${authUrl}`);

const rl = createInterface({
input: process.stdin,
output: process.stdout,
});

Logger.line();
// @ts-expect-error Defined method at the top of the file
const code = await rl.questionAsync("Enter the code from that page here: ");

rl.close();

const { tokens } = await oAuth2Client.getToken(code);
token = tokens;

oAuth2Client.setCredentials(token);

await writeFile(TOKEN_PATH, JSON.stringify(token));

Logger.success(`Token stored at ${TOKEN_PATH}`);
Logger.line();
}
Logger.success("Authorized!");
return token;
};

const getAllDryRuns = async (
drive: drive_v3.Drive
): Promise<drive_v3.Schema$FileList> => {
Logger.line();
Logger.log("Fetching 'Dry Run Forms' Folder...");
const response = await drive.files.list({
q: "'1q8N4gJ7A9XXuW1APiaf_BT5dYxd8tVOc' in parents and trashed = false",
});
Logger.success("Fetched 'Dry Run Forms' Folder!");
return response.data;
};

const getDryRunData = async (
drive: drive_v3.Drive,
id: string
): Promise<drive_v3.Schema$File> => {
const itemResponse = await drive.files.get({
fileId: id,
fields: "name,trashed,modifiedTime",
});

const { data: fileData } = itemResponse;
return fileData;
};

const shouldDeleteFile = (fileData: drive_v3.Schema$File): boolean => {
const { modifiedTime, trashed } = fileData;
const oneMonthAgo = moment().subtract(1, "month");
const isStale = moment(modifiedTime).isBefore(oneMonthAgo);

return isStale && !trashed;
};

const deleteFile = async (drive: drive_v3.Drive, id: string) => {
Logger.warning(`This file is stale (>1 month since changes)`);
Logger.log("Deleting file...");
await drive.files.delete({
fileId: id,
});
Logger.success("Deleted file!");
};

cleanUpDryRuns();
39 changes: 0 additions & 39 deletions scripts/drive.ts

This file was deleted.

2 changes: 1 addition & 1 deletion src/Helpers/AppsScript/src/form-data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export const initializeForm = (
title,
DriveApp.getFolderById(
dryRun
? "1qfx3jwE7QE_TPgSuOHUn_s31FmcoUGEd"
? "1q8N4gJ7A9XXuW1APiaf_BT5dYxd8tVOc"
: "1fWj2K9WAQSxpC9jyOZkRfmOvY186I1Xf"
)
)
Expand Down
4 changes: 4 additions & 0 deletions src/Helpers/Logger/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,10 @@ class Logger {
console.log(message);
}

static line(): void {
console.log();
}

static coloredLog(
color: keyof typeof Logger.COLORS,
message: string,
Expand Down
1 change: 0 additions & 1 deletion src/script.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import Airtable from "airtable";

// Internals
import { getProjectSuccessData } from "./Helpers/Airtable";
// import { getSheetData, setSheetData, setUpSheets } from "./Helpers/Sheets";
import {
checkReminderNeeded,
checkRequiredFields,
Expand Down

0 comments on commit a49878c

Please sign in to comment.