Skip to content

Commit

Permalink
Issue 672 (#673)
Browse files Browse the repository at this point in the history
* 2.1.0

* Low impact changes (#619)

* dependencies clean-up

* types for child_process' spawnSync

* types for child_process' spawnSync + options fix

* linting

* Relative rootdir (#620)

* relative rootDir support

* relative rootDir support (untrackedFiles behavior changed)

* relative rootDir doc changes

* Cleanup before next pr (#621)

* prettier + sort imports

* splitLines types

* unused package 'connect'

* ucfirst, isOnline types

* ellipsize types

* redundant package 'fs-copy-file-sync'

* removing extra line

* // TODO

* packages dependencies update

* comment fix

* fixes

* nicer ellipsize typing

* better?

* Refactor `inquirer` package (#622)

* regroup `inquirer` into a single file

* fix typo

* linting

* switch to `find-up`

* switch to `find-up` & `strip-bom`

* dependencies update

* findUp implementation fix

* enum accessor fix

* fs-extra & typescript dependency fix

* linting

* dependencies clean-up (again)

* non any cast

* refactoring `logError`
  • Loading branch information
PopGoesTheWza authored and grant committed Aug 6, 2019
1 parent 8a60d87 commit ee16b6d
Show file tree
Hide file tree
Showing 16 changed files with 161 additions and 215 deletions.
20 changes: 7 additions & 13 deletions src/apiutils.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import { ERROR, getProjectId, logError, spinner } from './utils';
import { functionNamePrompt, functionNameSource } from './inquirer';
import { loadAPICredentials, serviceUsage } from './auth';

import { enableOrDisableAdvanceServiceInManifest } from './manifest';
import fuzzy from 'fuzzy';
import { script_v1 } from 'googleapis';
import { loadAPICredentials, serviceUsage } from './auth';
import { functionNamePrompt, functionNameSource } from './inquirer';
import { enableOrDisableAdvanceServiceInManifest } from './manifest';
import { ERROR, getProjectId, logError, spinner } from './utils';

/**
* Prompts for the function name.
Expand All @@ -15,10 +14,7 @@ export async function getFunctionNames(script: script_v1.Script, scriptId: strin
scriptId,
});
spinner.stop(true);
if (content.status !== 200) {
logError(content.statusText);
throw Error();
}
if (content.status !== 200) logError(content.statusText);
const files = content.data.files || [];
type TypeFunction = script_v1.Schema$GoogleAppsScriptTypeFunction;
const functionNames: string[] = files
Expand Down Expand Up @@ -51,7 +47,7 @@ export async function getFunctionNames(script: script_v1.Script, scriptId: strin
// TODO: unnecessary export
export async function getProjectIdWithErrors() {
const projectId = await getProjectId(); // will prompt user to set up if required
if (!projectId) throw logError(null, ERROR.NO_GCLOUD_PROJECT);
if (!projectId) logError(null, ERROR.NO_GCLOUD_PROJECT);
return projectId;
}

Expand All @@ -71,9 +67,7 @@ export async function isEnabled(serviceName: string) {
* @param {boolean} enable Enables the API if true, otherwise disables.
*/
export async function enableOrDisableAPI(serviceName: string, enable: boolean) {
if (!serviceName) {
logError(null, 'An API name is required. Try sheets');
}
if (!serviceName) logError(null, 'An API name is required. Try sheets');
const projectId = await getProjectIdWithErrors();
const name = `projects/${projectId}/services/${serviceName}.googleapis.com`;
try {
Expand Down
21 changes: 10 additions & 11 deletions src/auth.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,18 @@
import { ClaspCredentials, ERROR, LOG, checkIfOnline, getOAuthSettings, logError } from './utils';
import { ClaspToken, DOTFILE, Dotfile } from './dotfile';
import http from 'http';
// TODO: AddressInfo is not defined in @types/node version 8 => check if any impact
import { AddressInfo } from 'net';
import readline from 'readline';
import url from 'url';
/**
* Authentication with Google's APIs.
*/
import { Credentials, GenerateAuthUrlOpts, OAuth2Client, OAuth2ClientOptions } from 'google-auth-library';
import { google, script_v1 } from 'googleapis';

// TODO: AddressInfo is not defined in @types/node version 8 => check if any impact
import { AddressInfo } from 'net';
import http from 'http';
import { oauthScopesPrompt } from './inquirer';
import open from 'open';
import { ClaspToken, DOTFILE, Dotfile } from './dotfile';
import { oauthScopesPrompt } from './inquirer';
import { readManifest } from './manifest';
import readline from 'readline';
import url from 'url';
import { ClaspCredentials, ERROR, LOG, checkIfOnline, getOAuthSettings, logError } from './utils';

// Auth is complicated. Consider yourself warned.
// tslint:disable:max-line-length
Expand Down Expand Up @@ -137,7 +136,7 @@ export async function authorize(options: {
'https://www.googleapis.com/auth/cloud-platform',
];
// TODO formal error
// return logError(null, 'You need to specify scopes in the manifest.' +
// logError(null, 'You need to specify scopes in the manifest.' +
// 'View appsscript.json. Add a list of scopes in "oauthScopes"' +
// 'Tip:' +
// '1. clasp open' +
Expand Down Expand Up @@ -330,7 +329,7 @@ export async function checkOauthScopes(rc: ClaspToken) {
await oauthScopesPrompt()
.then(async (answers) => {
if (answers.doAuth) {
if (!rc.isLocalCreds) return logError(null, ERROR.NO_LOCAL_CREDENTIALS);
if (!rc.isLocalCreds) logError(null, ERROR.NO_LOCAL_CREDENTIALS);
await authorize({
useLocalhost: answers.localhost,
scopes: newScopes,
Expand Down
25 changes: 11 additions & 14 deletions src/commands/clone.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { async } from 'rxjs/internal/scheduler/async';
import { drive, loadAPICredentials } from '../auth';
import { fetchProject, hasProject, writeProjectFiles } from '../files';
import { ScriptIdPrompt, scriptIdPrompt } from '../inquirer';
Expand All @@ -17,7 +18,7 @@ const padEnd = require('string.prototype.padend');
*/
export default async (scriptId: string, versionNumber: number, cmd: { rootDir: string }) => {
await checkIfOnline();
if (hasProject()) return logError(null, ERROR.FOLDER_EXISTS);
if (hasProject()) logError(null, ERROR.FOLDER_EXISTS);
scriptId = scriptId ? extractScriptId(scriptId) : await getScriptId();
spinner.setSpinnerTitle(LOG.CLONING);
const rootDir = cmd.rootDir;
Expand All @@ -39,19 +40,15 @@ const getScriptId = async () => {
q: 'mimeType="application/vnd.google-apps.script"',
});
const data = list.data;
if (!data) {
logError(list.statusText, 'Unable to use the Drive API.');
return '';
}
if (!data) logError(list.statusText, 'Unable to use the Drive API.');
const files = data.files;
if (!files || !files.length) {
logError(null, LOG.FINDING_SCRIPTS_DNE);
return '';
if (files && files.length) {
const fileIds: ScriptIdPrompt[] = files.map(file => ({
name: `${padEnd(file.name, 20)}${LOG.SCRIPT_LINK(file.id || '')}`,
value: file.id || '',
}));
const answers = await scriptIdPrompt(fileIds);
return answers.scriptId;
}
const fileIds: ScriptIdPrompt[] = files.map(file => ({
name: `${padEnd(file.name, 20)}${LOG.SCRIPT_LINK(file.id || '')}`,
value: file.id || '',
}));
const answers = await scriptIdPrompt(fileIds);
return answers.scriptId;
return logError(null, LOG.FINDING_SCRIPTS_DNE);
};
51 changes: 22 additions & 29 deletions src/commands/create.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
import { SCRIPT_TYPES } from '../apis';
import { drive, loadAPICredentials, script } from '../auth';
import { fetchProject, hasProject, writeProjectFiles } from '../files';
import { scriptTypePrompt } from '../inquirer';
import { manifestExists } from '../manifest';
import {
ERROR,
LOG,
Expand All @@ -8,12 +13,6 @@ import {
saveProject,
spinner,
} from '../utils';
import { drive, loadAPICredentials, script } from '../auth';
import { fetchProject, hasProject, writeProjectFiles } from '../files';

import { SCRIPT_TYPES } from '../apis';
import { manifestExists } from '../manifest';
import { scriptTypePrompt } from '../inquirer';

/**
* Creates a new Apps Script project.
Expand All @@ -26,7 +25,7 @@ import { scriptTypePrompt } from '../inquirer';
export default async (cmd: { type: string; title: string; parentId: string; rootDir: string }) => {
// Handle common errors.
await checkIfOnline();
if (hasProject()) return logError(null, ERROR.FOLDER_EXISTS);
if (hasProject()) logError(null, ERROR.FOLDER_EXISTS);
await loadAPICredentials();

// Create defaults.
Expand Down Expand Up @@ -65,10 +64,7 @@ export default async (cmd: { type: string; title: string; parentId: string; root
spinner.setSpinnerTitle(LOG.CREATE_PROJECT_START(title)).start();
try {
const { scriptId } = await getProjectSettings(true);
if (scriptId) {
logError(null, ERROR.NO_NESTED_PROJECTS);
process.exit(1);
}
if (scriptId) logError(null, ERROR.NO_NESTED_PROJECTS);
} catch (err) {
// no scriptId (because project doesn't exist)
// console.log(err);
Expand All @@ -83,24 +79,21 @@ export default async (cmd: { type: string; title: string; parentId: string; root
});
spinner.stop(true);
if (res.status !== 200) {
if (parentId) {
console.log(res.statusText, ERROR.CREATE_WITH_PARENT);
}
if (parentId) console.log(res.statusText, ERROR.CREATE_WITH_PARENT);
logError(res.statusText, ERROR.CREATE);
} else {
const createdScriptId = res.data.scriptId || '';
console.log(LOG.CREATE_PROJECT_FINISH(type, createdScriptId));
const rootDir = cmd.rootDir;
saveProject(
{
scriptId: createdScriptId,
rootDir,
},
false,
);
if (!manifestExists(rootDir)) {
const files = await fetchProject(createdScriptId); // fetches appsscript.json, o.w. `push` breaks
writeProjectFiles(files, rootDir); // fetches appsscript.json, o.w. `push` breaks
}
}
const createdScriptId = res.data.scriptId || '';
console.log(LOG.CREATE_PROJECT_FINISH(type, createdScriptId));
const rootDir = cmd.rootDir;
saveProject(
{
scriptId: createdScriptId,
rootDir,
},
false,
);
if (!manifestExists(rootDir)) {
const files = await fetchProject(createdScriptId); // fetches appsscript.json, o.w. `push` breaks
writeProjectFiles(files, rootDir); // fetches appsscript.json, o.w. `push` breaks
}
};
11 changes: 3 additions & 8 deletions src/commands/deploy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,7 @@ export default async (cmd: { versionNumber: number; description: string; deploym
},
});
spinner.stop(true);
if (version.status !== 200) {
return logError(null, ERROR.ONE_DEPLOYMENT_CREATE);
}
if (version.status !== 200) logError(null, ERROR.ONE_DEPLOYMENT_CREATE);
versionNumber = version.data.versionNumber || 0;
console.log(LOG.VERSION_CREATED(versionNumber));
}
Expand Down Expand Up @@ -67,9 +65,6 @@ export default async (cmd: { versionNumber: number; description: string; deploym
});
}
spinner.stop(true);
if (deployments.status !== 200) {
logError(null, ERROR.DEPLOYMENT_COUNT);
} else {
console.log(`- ${deployments.data.deploymentId} @${versionNumber}.`);
}
if (deployments.status !== 200) logError(null, ERROR.DEPLOYMENT_COUNT);
console.log(`- ${deployments.data.deploymentId} @${versionNumber}.`);
};
11 changes: 4 additions & 7 deletions src/commands/deployments.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import { LOG, checkIfOnline, getProjectSettings, logError, spinner } from '../utils';
import { loadAPICredentials, script } from '../auth';

import pluralize from 'pluralize';
import { script_v1 } from 'googleapis';
import pluralize from 'pluralize';
import { loadAPICredentials, script } from '../auth';
import { LOG, checkIfOnline, getProjectSettings, logError, spinner } from '../utils';

/**
* Lists a script's deployments.
Expand All @@ -17,9 +16,7 @@ export default async () => {
scriptId,
});
spinner.stop(true);
if (deployments.status !== 200) {
return logError(deployments.statusText);
}
if (deployments.status !== 200) logError(deployments.statusText);
const deploymentsList = deployments.data.deployments || [];
const numDeployments = deploymentsList.length;
const deploymentWord = pluralize('Deployment', numDeployments);
Expand Down
4 changes: 1 addition & 3 deletions src/commands/list.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,7 @@ export default async () => {
q: 'mimeType="application/vnd.google-apps.script"',
});
spinner.stop(true);
if (filesList.status !== 200) {
return logError(null, ERROR.DRIVE);
}
if (filesList.status !== 200) logError(null, ERROR.DRIVE);
const files = filesList.data.files || [];
if (!files.length) {
return console.log(LOG.FINDING_SCRIPTS_DNE);
Expand Down
27 changes: 11 additions & 16 deletions src/commands/logs.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import { DOTFILE, ProjectSettings } from '../dotfile';
import { ERROR, LOG, checkIfOnline, getProjectSettings, isValidProjectId, logError, spinner } from '../utils';
import { loadAPICredentials, logger } from '../auth';

import { GaxiosResponse } from 'gaxios';
import { URL } from '../urls';
import chalk from 'chalk';
import { GaxiosResponse } from 'gaxios';
import { logging_v2 } from 'googleapis';
import open from 'open';
import { loadAPICredentials, logger } from '../auth';
import { DOTFILE, ProjectSettings } from '../dotfile';
import { projectIdPrompt } from '../inquirer';
import { URL } from '../urls';
import { ERROR, LOG, checkIfOnline, getProjectSettings, isValidProjectId, logError, spinner } from '../utils';

const padEnd = require('string.prototype.padend');

Expand Down Expand Up @@ -133,37 +132,33 @@ export function printLogs(
// TODO: unnecessary export
export async function setupLogs(): Promise<string> {
let projectId: string;
const promise = new Promise<string>((resolve, reject) => {
return new Promise<string>((resolve, reject) => {
getProjectSettings().then(projectSettings => {
console.log(`${LOG.OPEN_LINK(LOG.SCRIPT_LINK(projectSettings.scriptId))}\n`);
console.log(`${LOG.GET_PROJECT_ID_INSTRUCTIONS}\n`);
projectIdPrompt()
.then(answers => {
projectId = answers.projectId;
const dotfile = DOTFILE.PROJECT();
if (!dotfile) return reject(logError(null, ERROR.SETTINGS_DNE));
if (!dotfile) logError(null, ERROR.SETTINGS_DNE);
dotfile
.read<ProjectSettings>()
.then(settings => {
if (!settings.scriptId) logError(ERROR.SCRIPT_ID_DNE);
dotfile.write({ ...settings, ...{ projectId } });
resolve(projectId);
})
.catch((err: object) => {
reject(logError(err));
});
.catch((err: object) => logError(err));
})
.catch((err: Error) => {
console.log(err);
reject();
});
});
});
promise.catch(err => {
}).catch(err => {
spinner.stop(true);
throw logError(err);
return logError(err);
});
return promise;
}

/**
Expand All @@ -190,7 +185,7 @@ export async function fetchAndPrintLogs(
return logError(null, ERROR.NO_GCLOUD_PROJECT);
}
if (!isValidProjectId(projectId)) {
return logError(null, ERROR.PROJECT_ID_INCORRECT(projectId));
logError(null, ERROR.PROJECT_ID_INCORRECT(projectId));
}
try {
const logs = await logger.entries.list({
Expand Down

0 comments on commit ee16b6d

Please sign in to comment.