Skip to content

Commit

Permalink
chore: complexity in build (#1557)
Browse files Browse the repository at this point in the history
## Description

Build.ts


```bash
   74:13  warning  Async arrow function has too many statements (54). Maximum allowed is 20          max-statements
   74:13  warning  Async arrow function has a complexity of 18. Maximum allowed is 10                complexity
  251:8   warning  Async function 'buildModule' has too many statements (35). Maximum allowed is 20  max-statements
```

## Related Issue

Fixes #1539 
<!-- or -->
Relates to #

## Type of change

- [ ] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [x] Other (security config, docs update, etc)

## Checklist before merging
- [x] Unit,
[Journey](https://github.com/defenseunicorns/pepr/tree/main/journey),
[E2E Tests](https://github.com/defenseunicorns/pepr-excellent-examples),
[docs](https://github.com/defenseunicorns/pepr/tree/main/docs),
[adr](https://github.com/defenseunicorns/pepr/tree/main/adr) added or
updated as needed
- [x] [Contributor Guide
Steps](https://docs.pepr.dev/main/contribute/#submitting-a-pull-request)
followed

---------

Signed-off-by: Case Wylie <[email protected]>
Co-authored-by: Sam Mayer <[email protected]>
  • Loading branch information
cmwylie19 and samayer12 authored Dec 11, 2024
1 parent a7989f7 commit 0e50003
Show file tree
Hide file tree
Showing 3 changed files with 527 additions and 139 deletions.
180 changes: 180 additions & 0 deletions src/cli/build.helpers.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,15 @@
import { createDirectoryIfNotExists } from "../lib/filesystemService";
import { sanitizeResourceName } from "../sdk/sdk";
import { createDockerfile } from "../lib/included-files";
import { execSync } from "child_process";
import { CapabilityExport } from "../lib/types";
import { validateCapabilityNames } from "../lib/helpers";
import { BuildOptions, BuildResult, context, BuildContext } from "esbuild";
import { Assets } from "../lib/assets";
import { resolve } from "path";
import { promises as fs } from "fs";

export type Reloader = (opts: BuildResult<BuildOptions>) => void | Promise<void>;
/**
* Determine the RBAC mode based on the CLI options and the module's config
* @param opts CLI options
Expand Down Expand Up @@ -26,3 +38,171 @@ export function determineRbacMode(
// if nothing is defined return admin, else return scoped
return cfg.pepr.rbacMode || "admin";
}

/**
* Handle the custom output directory
* @param outputDir the desired output directory
* @returns The desired output directory or the default one
*/

export async function handleCustomOutputDir(outputDir: string): Promise<string> {
const defaultOutputDir = "dist";
if (outputDir) {
try {
await createDirectoryIfNotExists(outputDir);
return outputDir;
} catch (error) {
console.error(`Error creating output directory: ${error.message}`);
process.exit(1);
}
}
return defaultOutputDir;
}

/**
* Check if the image is from Iron Bank and return the correct image
* @param registry The registry of the image
* @param image The image to check
* @param peprVersion The version of the PEPR controller
* @returns The image string
* @example
*/
export function checkIronBankImage(registry: string, image: string, peprVersion: string): string {
return registry === "Iron Bank"
? `registry1.dso.mil/ironbank/opensource/defenseunicorns/pepr/controller:v${peprVersion}`
: image;
}

/**
* Check if the image pull secret is a valid Kubernetes name
* @param imagePullSecret
* @returns boolean
*/
export function validImagePullSecret(imagePullSecretName: string): void {
if (imagePullSecretName) {
const error = "Invalid imagePullSecret. Please provide a valid name as defined in RFC 1123.";
if (sanitizeResourceName(imagePullSecretName) !== imagePullSecretName) {
// https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#dns-subdomain-names
console.error(error);
process.exit(1);
}
}
}

/**
* Constraint to majke sure customImage and registry are not both used
* @param customImage
* @param registry
* @returns
*/
export function handleCustomImage(customImage: string, registry: string): string {
let defaultImage = "";
if (customImage) {
if (registry) {
console.error(`Custom Image and registry cannot be used together.`);
process.exit(1);
}
defaultImage = customImage;
}
return defaultImage;
}

/**
* Creates and pushes a custom image for WASM or any other included files
* @param includedFiles
* @param peprVersion
* @param description
* @param image
*/
export async function handleCustomImageBuild(
includedFiles: string[],
peprVersion: string,
description: string,
image: string,
): Promise<void> {
if (includedFiles.length > 0) {
await createDockerfile(peprVersion, description, includedFiles);
execSync(`docker build --tag ${image} -f Dockerfile.controller .`, {
stdio: "inherit",
});
execSync(`docker push ${image}`, { stdio: "inherit" });
}
}

/**
* Disables embedding of deployment files into output module
* @param embed
* @param path
* @returns
*/
export function handleEmbedding(embed: boolean, path: string): void {
if (!embed) {
console.info(`✅ Module built successfully at ${path}`);
return;
}
}

/**
* Check if the capability names are valid
* @param capabilities The capabilities to check
*/
export function handleValidCapabilityNames(capabilities: CapabilityExport[]): void {
try {
// wait for capabilities to be loaded and test names
validateCapabilityNames(capabilities);
} catch (e) {
console.error(`Error loading capability:`, e);
process.exit(1);
}
}

/**
* Watch for changes in the module
* @param ctxCfg The build options
* @param reloader The reloader function
* @returns The build context
*/
export async function watchForChanges(
ctxCfg: BuildOptions,
reloader: Reloader | undefined,
): Promise<BuildContext<BuildOptions>> {
const ctx = await context(ctxCfg);

// If the reloader function is defined, watch the module for changes
if (reloader) {
await ctx.watch();
} else {
// Otherwise, just build the module once
await ctx.rebuild();
await ctx.dispose();
}

return ctx;
}

export async function generateYamlAndWriteToDisk(obj: {
uuid: string;
imagePullSecret: string;
outputDir: string;
assets: Assets;
zarf: string;
}): Promise<void> {
const { uuid, imagePullSecret, outputDir, assets, zarf } = obj;
const yamlFile = `pepr-module-${uuid}.yaml`;
const chartPath = `${uuid}-chart`;
const yamlPath = resolve(outputDir, yamlFile);
const yaml = await assets.allYaml(imagePullSecret);
const zarfPath = resolve(outputDir, "zarf.yaml");

let localZarf = "";
if (zarf === "chart") {
localZarf = assets.zarfYamlChart(chartPath);
} else {
localZarf = assets.zarfYaml(yamlFile);
}
await fs.writeFile(yamlPath, yaml);
await fs.writeFile(zarfPath, localZarf);

await assets.generateHelmChart(outputDir);
console.info(`✅ K8s resource for the module saved to ${yamlPath}`);
}
Loading

0 comments on commit 0e50003

Please sign in to comment.