Skip to content

Commit

Permalink
chore: beautify logs
Browse files Browse the repository at this point in the history
  • Loading branch information
7nohe committed May 21, 2024
1 parent f396103 commit d73e499
Show file tree
Hide file tree
Showing 5 changed files with 111 additions and 14 deletions.
1 change: 0 additions & 1 deletion examples/laravel10-app/docker-compose.yml
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
# For more information: https://laravel.com/docs/sail
version: '3'
services:
laravel.test:
build:
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
"dependencies": {
"@7nohe/laravel-zodgen": "^0.1.6",
"commander": "^12.0.0",
"consola": "^3.2.3",
"glob": "^10.3.12",
"php-parser": "^3.1.5",
"typescript": "^5.4.5"
Expand Down
9 changes: 9 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

17 changes: 14 additions & 3 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ import {
} from "./constants";
import fs from "fs";
import { defaultFormRequestPath } from "@7nohe/laravel-zodgen";
import { consola } from "consola";
import { colors } from "consola/utils";
import path from "path";

export type CLIOptions = {
output: string;
Expand Down Expand Up @@ -46,14 +49,22 @@ program

const options = program.opts<CLIOptions>();

console.log(`Generating types...`);
consola.box(`${colors.bgBlueBright(`Laravel Typegen v${packageJson.version}`)}
[Options]
${Object.entries(options)
.map(([key, value]) => `${key}: ${value}`)
.join("\n")}
`);

try {
generate(options).then(() => {
console.log(`Types generated successfully!!`);
consola.success(
`Done! Generated types are available in ${path.resolve(options.output)}`
);
});
} catch {
console.log("Failed to generate types.");
consola.error("Failed to generate types.");
if (fs.existsSync(tmpDir) && process.env.KEEP_LARAVEL_JSON !== "true") {
// Clean up
fs.rmSync(tmpDir, { recursive: true });
Expand Down
97 changes: 87 additions & 10 deletions src/generate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,19 @@ import path from "path";
import { parseFormRequests } from "@7nohe/laravel-zodgen";
import { createFormRequestTypes } from "./formRequests/createFormRequestTypes";
import { formatNamespaceForCommand, getPhpAst, getPhpNamespace } from "./utils";
import { consola } from "consola";
import { colors } from "consola/utils";

const modelLogPrefix = colors.bgBlueBright("[Model]");
const routeLogPrefix = colors.bgGreenBright("[Route]");
const formRequestLogPrefix = colors.bgYellowBright("[FormRequest]");

export async function generate(options: CLIOptions) {
consola.info(
modelLogPrefix,
colors.blueBright("Start generating model types...")
);

const parsedModelPath = path
.join(options.modelPath, "**", "*.php")
.replace(/\\/g, "/");
Expand Down Expand Up @@ -48,32 +59,46 @@ export async function generate(options: CLIOptions) {
getNamespaceForCommand(modelPath) + "\\\\" + modelName;
const outputPath = path.join(tmpDir, `${modelName}.json`);

const modelShowCommand = `php artisan model:show ${namespacedModel} --json > ${outputPath}`;
const modelShowCommand = `php artisan model:show ${namespacedModel} --json`;

// Run artisan command to get model data
try {
if (process.env.SKIP_ARTISAN_COMMAND !== "true") {
execSync(modelShowCommand);
consola.start(
modelLogPrefix,
`Running '${colors.blueBright(modelShowCommand)}'`
);
const json = execSync(modelShowCommand).toString();
const dir = path.dirname(outputPath);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
fs.writeFileSync(outputPath, json);
consola.success(modelLogPrefix, `Saved ${modelName} to ${outputPath}`);
} else {
console.log(`Skipping ${modelShowCommand}`);
consola.info(modelLogPrefix, `Skipping ${modelShowCommand}`);
}
} catch (e) {
console.log(
consola.info(
modelLogPrefix,
`Failed to get model data for ${modelName}'. You still can generate types by running ${modelShowCommand} manually and then run 'laravel-typegen' with SKIP_ARTISAN_COMMAND=true environment variable.`
);
console.error(e);
consola.error(modelLogPrefix, e);
}

// Read model data from JSON file
try {
const jsonPath = path.resolve(tmpDir, `${modelName}.json`);
console.log(`Reading ${jsonPath}`);
consola.start(modelLogPrefix, `Reading ${jsonPath}`);
const modelJson = JSON.parse(
fs.readFileSync(jsonPath, "utf8")
) as LaravelModelType;
modelData.push(modelJson);
} catch {
console.log(`Failed to generate ${modelName}. Skipping...`);
consola.warn(
modelLogPrefix,
`Failed to generate ${modelName}. Skipping...`
);
}
}

Expand All @@ -85,16 +110,43 @@ export async function generate(options: CLIOptions) {
);
print(modelFileName, modelSource, options.output ?? defaultOutputPath);

consola.success(
modelLogPrefix,
colors.blueBright("Model types generated successfully.")
);

// Generate types for ziggy
if (options.ziggy) {
consola.info(
routeLogPrefix,
colors.greenBright("Start generating route types...")
);

const vendorOption = options.vendorRoutes ? "" : "--except-vendor";
const routeListCommand = `php artisan route:list ${vendorOption} --json > ${tmpDir}/route.json`;
const routeListCommand = `php artisan route:list ${vendorOption} --json`;

if (process.env.SKIP_ARTISAN_COMMAND !== "true") {
execSync(routeListCommand);
consola.start(
routeLogPrefix,
`Running '${colors.greenBright(routeListCommand)}'`
);
const json = execSync(routeListCommand).toString();
const dir = path.dirname(path.resolve(tmpDir, "route.json"));
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, {
recursive: true,
});
}
fs.writeFileSync(path.resolve(tmpDir, "route.json"), json);
consola.success(
routeLogPrefix,
`Saved route.json to ${path.resolve(tmpDir, "route.json")}`
);
} else {
console.log(`Skipping ${routeListCommand}`);
consola.warn(routeLogPrefix, `Failed to get route data. Skipping...`);
}

consola.start(routeLogPrefix, "Reading route.json");
const routeJson = JSON.parse(
fs.readFileSync(path.resolve(tmpDir, "route.json"), "utf8")
) as LaravelRouteListType[];
Expand All @@ -111,6 +163,8 @@ export async function generate(options: CLIOptions) {
options.output ?? defaultOutputPath
);

consola.start(routeLogPrefix, "Copying route.d.ts...");

// Copy route.d.ts
if (!options.ignoreRouteDts) {
fs.copyFileSync(
Expand All @@ -121,20 +175,43 @@ export async function generate(options: CLIOptions) {
)
);
}

consola.success(
routeLogPrefix,
colors.greenBright("Route types generated successfully.")
);
}

if (options.formRequest) {
consola.start(
formRequestLogPrefix,
colors.yellowBright("Start generating form request types...")
);
consola.start(
formRequestLogPrefix,
`Parsing form requests from ${options.formRequestPath}...`
);
// Generate types for form requests
const rules = parseFormRequests(options.formRequestPath, true);
consola.success(formRequestLogPrefix, "Form requests parsed successfully.");

const formRequestSource = createFormRequestTypes(rules);
print(
formRequestsFileName,
formRequestSource,
options.output ?? defaultOutputPath
);

consola.success(
formRequestLogPrefix,
colors.yellowBright("Form request types generated successfully.")
);
}

if (fs.existsSync(tmpDir) && process.env.KEEP_LARAVEL_JSON !== "true") {
consola.start("Removing temporary files...");
fs.rmSync(tmpDir, { recursive: true });
consola.success("Temporary files removed.");
}
}

Expand Down

0 comments on commit d73e499

Please sign in to comment.