Skip to content

Commit

Permalink
Merge branch 'master' into alexcheema/docker-parcel-bundler
Browse files Browse the repository at this point in the history
  • Loading branch information
mergify[bot] committed May 1, 2020
2 parents 711b58e + 0e96415 commit 8de8246
Show file tree
Hide file tree
Showing 7 changed files with 81 additions and 29 deletions.
4 changes: 2 additions & 2 deletions packages/@aws-cdk/aws-appsync/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,8 @@ export class ApiStack extends Stack {
constructor(scope: Construct, id: string) {
super(scope, id);

const userPool = new UserPool(this, 'UserPool', {
signInType: SignInType.USERNAME,
const userPool = new UserPool(this, 'UserPool'{
userPoolName: 'myPool',
});

const api = new GraphQLApi(this, 'Api', {
Expand Down
27 changes: 17 additions & 10 deletions packages/aws-cdk/lib/api/aws-auth/account-cache.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as fs from 'fs-extra';
import * as os from 'os';
import * as path from 'path';
import { debug } from '../../logging';
import { cdkCacheDir } from '../../util/directories';
import { Account } from './sdk-provider';

/**
Expand All @@ -22,7 +22,7 @@ export class AccountAccessKeyCache {
* @param filePath Path to the cache file
*/
constructor(filePath?: string) {
this.cacheFile = filePath || path.join(os.homedir(), '.cdk', 'cache', 'accounts_partitions.json');
this.cacheFile = filePath || path.join(cdkCacheDir(), 'accounts_partitions.json');
}

/**
Expand Down Expand Up @@ -77,18 +77,25 @@ export class AccountAccessKeyCache {
}

private async loadMap(): Promise<{ [accessKeyId: string]: Account }> {
if (!(await fs.pathExists(this.cacheFile))) {
return { };
try {
return await fs.readJson(this.cacheFile);
} catch (e) {
// File doesn't exist or is not readable. This is a cache,
// pretend we successfully loaded an empty map.
if (e.code === 'ENOENT' || e.code === 'EACCES') { return {}; }
throw e;
}

return await fs.readJson(this.cacheFile);
}

private async saveMap(map: { [accessKeyId: string]: Account }) {
if (!(await fs.pathExists(this.cacheFile))) {
await fs.mkdirs(path.dirname(this.cacheFile));
try {
await fs.ensureFile(this.cacheFile);
await fs.writeJson(this.cacheFile, map, { spaces: 2 });
} catch (e) {
// File doesn't exist or file/dir isn't writable. This is a cache,
// if we can't write it then too bad.
if (e.code === 'ENOENT' || e.code === 'EACCES') { return; }
throw e;
}

await fs.writeJson(this.cacheFile, map, { spaces: 2 });
}
}
5 changes: 2 additions & 3 deletions packages/aws-cdk/lib/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ import * as cxapi from '@aws-cdk/cx-api';
import * as childProcess from 'child_process';
import * as colors from 'colors/safe';
import * as fs from 'fs-extra';
import * as os from 'os';
import * as path from 'path';
import { error, print, warning } from './logging';
import { cdkHomeDir } from './util/directories';

export type InvokeHook = (targetDirectory: string) => Promise<void>;

Expand All @@ -16,7 +16,6 @@ const decamelize = require('decamelize');
// tslint:enable:no-var-requires

const TEMPLATES_DIR = path.join(__dirname, 'init-templates');
const CDK_HOME = process.env.CDK_HOME ? path.resolve(process.env.CDK_HOME) : path.join(os.homedir(), '.cdk');

/**
* Initialize a CDK package in the current directory
Expand Down Expand Up @@ -165,7 +164,7 @@ export class InitTemplate {
.replace(/%name\.camelCased%/g, camelCase(project.name))
.replace(/%name\.PascalCased%/g, camelCase(project.name, { pascalCase: true }))
.replace(/%cdk-version%/g, cdkVersion)
.replace(/%cdk-home%/g, CDK_HOME)
.replace(/%cdk-home%/g, cdkHomeDir())
.replace(/%name\.PythonModule%/g, project.name.replace(/-/g, '_'))
.replace(/%python-executable%/g, pythonExecutable())
.replace(/%name\.StackName%/g, project.name.replace(/[^A-Za-z0-9-]/g, '-'));
Expand Down
12 changes: 12 additions & 0 deletions packages/aws-cdk/lib/util/directories.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import * as os from 'os';
import * as path from 'path';

export function cdkHomeDir() {
return process.env.CDK_HOME
? path.resolve(process.env.CDK_HOME)
: path.join((os.userInfo().homedir ?? os.homedir()).trim() || '/', '.cdk');
}

export function cdkCacheDir() {
return path.join(cdkHomeDir(), 'cache');
}
9 changes: 2 additions & 7 deletions packages/aws-cdk/lib/version.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { exec as _exec } from 'child_process';
import * as colors from 'colors/safe';
import * as fs from 'fs-extra';
import * as os from 'os';
import * as path from 'path';
import * as semver from 'semver';
import { promisify } from 'util';
import { debug, print } from '../lib/logging';
import { formatAsBanner } from '../lib/util/console-formatters';
import { cdkCacheDir } from './util/directories';

const ONE_DAY_IN_SECONDS = 1 * 24 * 60 * 60;

Expand All @@ -26,13 +26,8 @@ function commit(): string {

export class VersionCheckTTL {
public static timestampFilePath(): string {
// Get the home directory from the OS, first. Fallback to $HOME.
const homedir = os.userInfo().homedir || os.homedir();
if (!homedir || !homedir.trim()) {
throw new Error('Cannot determine home directory');
}
// Using the same path from account-cache.ts
return path.join(homedir, '.cdk', 'cache', 'repo-version-ttl');
return path.join(cdkCacheDir(), 'repo-version-ttl');
}

private readonly file: string;
Expand Down
46 changes: 46 additions & 0 deletions packages/aws-cdk/test/account-cache.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,27 @@ async function nukeCache(cacheDir: string) {
await fs.remove(cacheDir);
}

test('default account cache uses CDK_HOME', () => {
process.env.CDK_HOME = '/banana';
const cache = new AccountAccessKeyCache();
expect((cache as any).cacheFile).toContain('/banana/');
});

test('account cache does not fail when given a nonwritable directory', async () => {
const accessError = new Error('Oh no');
(accessError as any).code = 'EACCES';

return withMocked(fs, 'mkdirs', async (mkdirs) => {
// Have to do this because mkdirs has 2 overloads and it confuses TypeScript
(mkdirs as unknown as jest.Mock<Promise<void>, [any]>).mockRejectedValue(accessError);

const cache = new AccountAccessKeyCache('/abc/xyz');
await cache.fetch('xyz', () => Promise.resolve({ accountId: 'asdf', partition: 'swa' }));

// No exception
});
});

test('get(k) when cache is empty', async () => {
const { cacheDir, cacheFile, cache } = await makeCache();
try {
Expand Down Expand Up @@ -89,3 +110,28 @@ test(`cache is nuked if it exceeds ${AccountAccessKeyCache.MAX_ENTRIES} entries`
await nukeCache(cacheDir);
}
});

function withMocked<A extends object, K extends keyof A, B>(obj: A, key: K, block: (fn: jest.Mocked<A>[K]) => B): B {
const original = obj[key];
const mockFn = jest.fn();
(obj as any)[key] = mockFn;

let ret;
try {
ret = block(mockFn as any);
} catch (e) {
obj[key] = original;
throw e;
}

if (!isPromise(ret)) {
obj[key] = original;
return ret;
}

return ret.finally(() => { obj[key] = original; }) as any;
}

function isPromise<A>(object: any): object is Promise<A> {
return Promise.resolve(object) === object;
}
7 changes: 0 additions & 7 deletions packages/aws-cdk/test/version.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import * as fs from 'fs-extra';
import * as os from 'os';
import * as path from 'path';
import * as sinon from 'sinon';
import { setTimeout as _setTimeout } from 'timers';
Expand Down Expand Up @@ -58,12 +57,6 @@ test('Return null if version is higher than npm', async () => {
expect(result).toBeNull();
});

test('No homedir for the given user', () => {
sinon.stub(os, 'homedir').returns('');
sinon.stub(os, 'userInfo').returns({ username: '', uid: 10, gid: 11, shell: null, homedir: ''});
expect(() => new VersionCheckTTL()).toThrow(/Cannot determine home directory/);
});

test('Version specified is stored in the TTL file', async () => {
const cacheFile = tmpfile();
const cache = new VersionCheckTTL(cacheFile, 1);
Expand Down

0 comments on commit 8de8246

Please sign in to comment.