Skip to content

Commit

Permalink
Merge pull request #705 from OpenFn/prettier
Browse files Browse the repository at this point in the history
Run prettier
  • Loading branch information
josephjclark authored May 28, 2024
2 parents dc117fb + 2fedc86 commit ae72486
Show file tree
Hide file tree
Showing 12 changed files with 111 additions and 90 deletions.
63 changes: 33 additions & 30 deletions packages/cli/src/docs/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,36 +13,40 @@ import type {
import { getNameAndVersion, getLatestVersion } from '@openfn/runtime';
import expandAdaptors from '../util/expand-adaptors';

const describeFn = (adaptorName: string, fn: FunctionDescription) => [
c.green(`## ${
fn.name
}(${fn.parameters.map(({ name }) => name).join(',')})`),
`${fn.description}`,
c.green('### Usage Examples'),
fn.examples.length
? fn.examples
.map(({ code, caption }) => {
if (caption) {
return `${caption}:\n${code}`;
}
return code;
})
.join('\n\n')
: 'None',
c.green('### API Reference'),
`https://docs.openfn.org/adaptors/packages/${adaptorName.replace(
'@openfn/language-',
''
)}-docs#${fn.name}
`].join('\n\n');
const describeFn = (adaptorName: string, fn: FunctionDescription) =>
[
c.green(
`## ${fn.name}(${fn.parameters.map(({ name }) => name).join(',')})`
),
`${fn.description}`,
c.green('### Usage Examples'),
fn.examples.length
? fn.examples
.map(({ code, caption }) => {
if (caption) {
return `${caption}:\n${code}`;
}
return code;
})
.join('\n\n')
: 'None',
c.green('### API Reference'),
`https://docs.openfn.org/adaptors/packages/${adaptorName.replace(
'@openfn/language-',
''
)}-docs#${fn.name}
`,
].join('\n\n');

const describeLib = (
adaptorName: string,
data: PackageDescription
) => c.green(`## ${adaptorName} ${data.version}`) + `
const describeLib = (adaptorName: string, data: PackageDescription) =>
c.green(`## ${adaptorName} ${data.version}`) +
`
${data.functions
.map((fn) => ` ${c.yellow(fn.name)} (${fn.parameters.map((p) => p.name).join(', ')})`)
.map(
(fn) =>
` ${c.yellow(fn.name)} (${fn.parameters.map((p) => p.name).join(', ')})`
)
.sort()
.join('\n')}
`;
Expand Down Expand Up @@ -87,7 +91,7 @@ const docsHandler = async (
const fn = data.functions.find(({ name }) => name === operation);
if (fn) {
logger.debug('Operation schema:', fn);
logger.break()
logger.break();

// Generate a documentation string
desc = describeFn(name, fn);
Expand All @@ -98,7 +102,6 @@ const docsHandler = async (
logger.debug('No operation name provided');
logger.always('Available functions:\n');
desc = describeLib(name, data);

}
// Log the description without any ceremony/meta stuff from the logger
logger.print(desc);
Expand All @@ -107,7 +110,7 @@ const docsHandler = async (
logger.always(`For more details on a specfic functions, use:
openfn docs ${name} <fn>
`)
`);
}

if (didError) {
Expand Down
3 changes: 2 additions & 1 deletion packages/cli/src/metadata/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,8 @@ export const getAdaptorPath = async (
return adaptorPath;
};

export const shouldAutoinstall = (adaptor: string): boolean => adaptor?.length > 0 && !adaptor.startsWith('/') && !adaptor.includes('=');
export const shouldAutoinstall = (adaptor: string): boolean =>
adaptor?.length > 0 && !adaptor.startsWith('/') && !adaptor.includes('=');

const metadataHandler = async (options: MetadataOpts, logger: Logger) => {
const { repoDir, adaptors } = options;
Expand Down
30 changes: 19 additions & 11 deletions packages/cli/src/pull/command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,14 @@ import * as o from '../options';
export type PullOptions = Required<
Pick<
Opts,
'command' | 'log' | 'logJson' | 'statePath' | 'projectPath' | 'configPath' | 'projectId' | 'confirm'
| 'command'
| 'log'
| 'logJson'
| 'statePath'
| 'projectPath'
| 'configPath'
| 'projectId'
| 'confirm'
>
>;

Expand All @@ -16,16 +23,17 @@ const pullCommand: yargs.CommandModule<PullOptions> = {
command: 'pull [projectId]',
describe:
"Pull a project's state and spec from a Lightning Instance to the local directory",
builder: (yargs: yargs.Argv<PullOptions>) =>
build(options, yargs)
.positional('projectId', {
describe:
'The id of the project that should be pulled shouled be a UUID',
demandOption: true,
}).example(
'pull 57862287-23e6-4650-8d79-e1dd88b24b1c',
'Pull an updated copy of a the above spec and state from a Lightning Instance'
),
builder: (yargs: yargs.Argv<PullOptions>) =>
build(options, yargs)
.positional('projectId', {
describe:
'The id of the project that should be pulled shouled be a UUID',
demandOption: true,
})
.example(
'pull 57862287-23e6-4650-8d79-e1dd88b24b1c',
'Pull an updated copy of a the above spec and state from a Lightning Instance'
),
handler: ensure('pull', options),
};

Expand Down
8 changes: 4 additions & 4 deletions packages/cli/src/pull/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@ async function pullHandler(options: PullOptions, logger: Logger) {
try {
assertPath(options.projectId);
const config = mergeOverrides(await getConfig(options.configPath), options);
logger.always('Downloading existing project state (as JSON) from the server.');
logger.always(
'Downloading existing project state (as JSON) from the server.'
);

// Get the project.json from Lightning
const { data: project } = await getProject(config, options.projectId);
Expand All @@ -38,9 +40,7 @@ async function pullHandler(options: PullOptions, logger: Logger) {
JSON.stringify(state, null, 2)
);

logger.always(
'Downloading the project spec (as YAML) from the server.'
);
logger.always('Downloading the project spec (as YAML) from the server.');
// Get the project.yaml from Lightning
const url = new URL(
`api/provision/yaml?id=${options.projectId}`,
Expand Down
7 changes: 6 additions & 1 deletion packages/cli/src/test/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,12 @@ const testHandler = async (options: TestOptions, logger: Logger) => {

const state = await loadState(plan, opts, createNullLogger());
const compiledPlan = (await compile(plan, opts, logger)) as ExecutionPlan;
const result = await execute(compiledPlan, state, opts as ExecuteOptions, logger);
const result = await execute(
compiledPlan,
state,
opts as ExecuteOptions,
logger
);
logger.success(`Result: ${result.data.answer}`);
return result;
};
Expand Down
12 changes: 6 additions & 6 deletions packages/cli/src/util/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ export const saveToCache = async (
logger.info(`Writing ${stepId} output to ${cachePath}`);
fs.writeFileSync(cachePath, JSON.stringify(output));
}
}
};

export const clearCache = async (
plan: ExecutionPlan,
Expand All @@ -67,15 +67,15 @@ export const clearCache = async (
const cacheDir = await getCachePath(plan, options);

try {
await rmdir(cacheDir, { recursive: true })
await rmdir(cacheDir, { recursive: true });

logger.info(`Cleared cache at ${cacheDir}`);
} catch(e: any) {
} catch (e: any) {
if (e.code === 'ENOENT') {
// No cached files exist - this is fine, do nothing
} else {
logger.error(`Error while clearing cache at ${cacheDir}`)
logger.error(e)
logger.error(`Error while clearing cache at ${cacheDir}`);
logger.error(e);
}
}
}
};
4 changes: 2 additions & 2 deletions packages/cli/src/util/load-plan.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ const loadJson = async (workflowPath: string, logger: Logger): Promise<any> => {

try {
text = await fs.readFile(workflowPath, 'utf8');
logger.debug('Loaded workflow from', workflowPath)
logger.debug('Loaded workflow from', workflowPath);
} catch (e) {
return abort(
logger,
Expand Down Expand Up @@ -170,7 +170,7 @@ const fetchFile = async (
? filePath
: path.resolve(rootDir, filePath);
const result = await fs.readFile(fullPath, 'utf8');
log.debug('Loaded file', fullPath)
log.debug('Loaded file', fullPath);
return result;
} catch (e) {
abort(
Expand Down
28 changes: 16 additions & 12 deletions packages/compiler/src/transforms/lazy-state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@
*
* Converts all $.a.b chains unless:
* - $ was assigned previously in that scope
*
*
*
*/
import { builders as b, namedTypes as n} from 'ast-types';
import { builders as b, namedTypes as n } from 'ast-types';
import type { NodePath } from 'ast-types/lib/node-path';
import type { Transformer } from '../transform';

Expand All @@ -17,14 +17,14 @@ const ensureParentArrow = (path: NodePath<n.MemberExpression>) => {

// find the parenting call expression
// Ie, the operation we're passing this arrow into
while(root && !n.CallExpression.check(root.node)) {
while (root && !n.CallExpression.check(root.node)) {
last = root;
root = root.parent;

// if this is any kind of statement, we should throw
// TODO we may relax this, see https://github.com/OpenFn/kit/issues/660
if (n.Statement.check(root.node) || n.Declaration.check(root.node)) {
throw new Error(`invalid state operator: must be inside an expression`)
throw new Error(`invalid state operator: must be inside an expression`);
}
}

Expand All @@ -38,26 +38,30 @@ const ensureParentArrow = (path: NodePath<n.MemberExpression>) => {
}
} else {
// Actually I don't think we'll ever get here
throw new Error(`invalid state operator: must be be passed as an argument to an operator`)
throw new Error(
`invalid state operator: must be be passed as an argument to an operator`
);
}
}
};

// Checks whether the passed node is an open function, ie, (state) => {...}
const isOpenFunction = (path: NodePath) => {
// is it a function?
if (n.ArrowFunctionExpression.check(path.node)) {
if (n.ArrowFunctionExpression.check(path.node)) {
const arrow = path.node as n.ArrowFunctionExpression;
// does it have one param?
if(arrow.params.length == 1) {
const name = (arrow.params[0] as n.Identifier).name
if (arrow.params.length == 1) {
const name = (arrow.params[0] as n.Identifier).name;
// is the param called state?
if (name === "state") {
if (name === 'state') {
// We already have a valid open function here
return true;
}
throw new Error(`invalid state operator: parameter "${name}" should be called "state"`)
throw new Error(
`invalid state operator: parameter "${name}" should be called "state"`
);
}
throw new Error('invalid state operator: parent has wrong arity')
throw new Error('invalid state operator: parent has wrong arity');
}

// if we get here, then path is:
Expand Down
36 changes: 18 additions & 18 deletions packages/describe-package/src/fs/fake-fs.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
type System = import("typescript").System;
type System = import('typescript').System;

let hasLocalStorage = false;
try {
Expand All @@ -8,19 +8,19 @@ try {
const hasProcess = typeof process !== `undefined`;

const shouldDebug =
(hasLocalStorage && localStorage.getItem("DEBUG")) ||
(hasLocalStorage && localStorage.getItem('DEBUG')) ||
(hasProcess && process.env.DEBUG);

const debugLog = shouldDebug
? console.log
: (_message?: any, ..._optionalParams: any[]) => "";
: (_message?: any, ..._optionalParams: any[]) => '';

function notImplemented(methodName: string): any {
throw new Error(`Method '${methodName}' is not implemented.`);
}
//
// "/DOM.d.ts" => "/lib.dom.d.ts"
const libize = (path: string) => path.replace("/", "/lib.").toLowerCase();
const libize = (path: string) => path.replace('/', '/lib.').toLowerCase();

function audit<ArgsT extends any[], ReturnT>(
name: string,
Expand All @@ -29,9 +29,9 @@ function audit<ArgsT extends any[], ReturnT>(
return (...args) => {
const res = fn(...args);

const smallres = typeof res === "string" ? res.slice(0, 80) + "..." : res;
debugLog("> " + name, ...args);
debugLog("< " + smallres);
const smallres = typeof res === 'string' ? res.slice(0, 80) + '...' : res;
debugLog('> ' + name, ...args);
debugLog('< ' + smallres);

return res;
};
Expand All @@ -40,31 +40,31 @@ function audit<ArgsT extends any[], ReturnT>(
export function createSystem(files: Map<string, string>): System {
return {
args: [],
createDirectory: () => notImplemented("createDirectory"),
directoryExists: audit("directoryExists", (directory) => {
createDirectory: () => notImplemented('createDirectory'),
directoryExists: audit('directoryExists', (directory) => {
return Array.from(files.keys()).some((path) =>
path.startsWith(directory)
);
}),
exit: () => notImplemented("exit"),
exit: () => notImplemented('exit'),
fileExists: audit(
"fileExists",
'fileExists',
(fileName) => files.has(fileName) || files.has(libize(fileName))
),
getCurrentDirectory: () => "/",
getCurrentDirectory: () => '/',
getDirectories: () => [],
getExecutingFilePath: () => notImplemented("getExecutingFilePath"),
readDirectory: audit("readDirectory", (directory) =>
directory === "/" ? Array.from(files.keys()) : []
getExecutingFilePath: () => notImplemented('getExecutingFilePath'),
readDirectory: audit('readDirectory', (directory) =>
directory === '/' ? Array.from(files.keys()) : []
),
readFile: audit(
"readFile",
'readFile',
(fileName) => files.get(fileName) || files.get(libize(fileName))
),
resolvePath: (path) => path,
newLine: "\n",
newLine: '\n',
useCaseSensitiveFileNames: true,
write: () => notImplemented("write"),
write: () => notImplemented('write'),
writeFile: (fileName, contents) => {
files.set(fileName, contents);
},
Expand Down
Loading

0 comments on commit ae72486

Please sign in to comment.