Skip to content

Commit

Permalink
feat(php): Generate project (#4612)
Browse files Browse the repository at this point in the history
  • Loading branch information
amckinney authored Sep 11, 2024
1 parent c71a82f commit 63d33bb
Show file tree
Hide file tree
Showing 897 changed files with 15,773 additions and 99 deletions.
8 changes: 8 additions & 0 deletions generators/commons/src/AbstractGeneratorContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ const LOG_LEVEL_CONVERSIONS: Record<LogLevel, FernGeneratorExec.logging.LogLevel

export abstract class AbstractGeneratorContext {
public readonly logger: Logger;
public readonly version: string | undefined;

public constructor(
public readonly config: FernGeneratorExec.config.GeneratorConfig,
Expand All @@ -30,5 +31,12 @@ export abstract class AbstractGeneratorContext {
console.warn("Encountered error when sending update", e);
}
});

this.version = config?.output?.mode?._visit({
downloadFiles: () => undefined,
github: (github) => github.version,
publish: (publish) => publish.version,
_other: () => undefined
});
}
}
25 changes: 25 additions & 0 deletions generators/commons/src/project/AbstractProject.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { AbstractGeneratorContext } from "../AbstractGeneratorContext";
import { AbsoluteFilePath } from "@fern-api/fs-utils";
import { File } from "./File";

export abstract class AbstractProject<GeneratorContext extends AbstractGeneratorContext> {
public readonly absolutePathToOutputDirectory: AbsoluteFilePath;
public readonly rawFiles: File[] = [];

public constructor(public readonly context: GeneratorContext) {
this.absolutePathToOutputDirectory = AbsoluteFilePath.of(this.context.config.output.path);
}

public addRawFiles(file: File): void {
this.rawFiles.push(file);
}

public async writeRawFiles(): Promise<void> {
await Promise.all(this.rawFiles.map(async (file) => await file.write(this.absolutePathToOutputDirectory)));
}

/**
* Persists the project by writing it to disk.
*/
protected abstract persist(): Promise<void>;
}
1 change: 1 addition & 0 deletions generators/commons/src/project/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export { AbstractProject } from "./AbstractProject";
export { File } from "./File";
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,10 @@ export abstract class AbstractCsharpGeneratorContext<
this.namespace =
this.customConfig.namespace ??
upperFirst(camelCase(`${this.config.organization}_${this.ir.apiName.pascalCase.unsafeName}`));
this.project = new CsharpProject(this, this.namespace);
this.project = new CsharpProject({
context: this,
name: this.namespace
});
this.csharpTypeMapper = new CsharpTypeMapper(this);
this.csharpProtobufTypeMapper = new CsharpProtobufTypeMapper(this);
this.protobufResolver = new ProtobufResolver(this, this.csharpTypeMapper);
Expand Down Expand Up @@ -100,15 +103,6 @@ export abstract class AbstractCsharpGeneratorContext<
return `${this.getTestNamespace()}.Unit.MockServer`;
}

public getVersion(): string | undefined {
return this.config.output?.mode._visit({
downloadFiles: () => undefined,
github: (github) => github.version,
publish: (publish) => publish.version,
_other: () => undefined
});
}

public hasGrpcEndpoints(): boolean {
// TODO: Replace this with the this.ir.sdkConfig.hasGrpcEndpoints property (when available).
return Object.values(this.ir.services).some((service) => service.transport?.type === "grpc");
Expand Down
38 changes: 16 additions & 22 deletions generators/csharp/codegen/src/project/CsharpProject.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { AbsoluteFilePath, join, RelativeFilePath } from "@fern-api/fs-utils";
import { SourceFetcher, File } from "@fern-api/generator-commons";
import { SourceFetcher, File, AbstractProject } from "@fern-api/generator-commons";
import { loggingExeca } from "@fern-api/logging-execa";
import { mkdir, readFile, writeFile } from "fs/promises";
import { template } from "lodash-es";
Expand All @@ -19,24 +19,27 @@ export const PUBLIC_CORE_DIRECTORY_NAME = "Public";
/**
* In memory representation of a C# project.
*/
export class CsharpProject {
private rawFiles: File[] = [];
export class CsharpProject extends AbstractProject<AbstractCsharpGeneratorContext<BaseCsharpCustomConfigSchema>> {
private name: string;
private sourceFiles: CSharpFile[] = [];
private testFiles: CSharpFile[] = [];
private coreFiles: File[] = [];
private coreTestFiles: File[] = [];
private publicCoreFiles: File[] = [];
private publicCoreTestFiles: File[] = [];
private testUtilFiles: File[] = [];
private absolutePathToOutputDirectory: AbsoluteFilePath;
private sourceFetcher: SourceFetcher;
public readonly filepaths: CsharpProjectFilepaths;

public constructor(
private readonly context: AbstractCsharpGeneratorContext<BaseCsharpCustomConfigSchema>,
private readonly name: string
) {
this.absolutePathToOutputDirectory = AbsoluteFilePath.of(this.context.config.output.path);
public constructor({
context,
name
}: {
context: AbstractCsharpGeneratorContext<BaseCsharpCustomConfigSchema>;
name: string;
}) {
super(context);
this.name = name;
this.filepaths = new CsharpProjectFilepaths(name);
this.sourceFetcher = new SourceFetcher({
context: this.context,
Expand All @@ -48,10 +51,6 @@ export class CsharpProject {
return this.filepaths.getProjectDirectory();
}

public addRawFiles(file: File): void {
this.rawFiles.push(file);
}

public addCoreFiles(file: File): void {
this.coreFiles.push(file);
}
Expand Down Expand Up @@ -92,9 +91,7 @@ export class CsharpProject {
cwd: this.absolutePathToOutputDirectory
});

for (const file of this.rawFiles) {
await file.write(this.absolutePathToOutputDirectory);
}
await this.writeRawFiles();

for (const file of this.sourceFiles) {
await file.write(absolutePathToProjectDirectory);
Expand Down Expand Up @@ -192,7 +189,6 @@ export class CsharpProject {
const protobufSourceFilePaths = await this.sourceFetcher.copyProtobufSources(absolutePathToProtoDirectory);

const csproj = new CsProj({
version: this.context.getVersion(),
license: this.context.config.license?._visit({
custom: (val) => {
return val.filename;
Expand Down Expand Up @@ -452,15 +448,13 @@ declare namespace CsProj {
const FOUR_SPACES = " ";

class CsProj {
private version: string | undefined;
private license: string | undefined;
private githubUrl: string | undefined;
private packageId: string | undefined;
private context: AbstractCsharpGeneratorContext<BaseCsharpCustomConfigSchema>;
private protobufSourceFilePaths: RelativeFilePath[];

public constructor({ version, license, githubUrl, context, protobufSourceFilePaths }: CsProj.Args) {
this.version = version;
public constructor({ license, githubUrl, context, protobufSourceFilePaths }: CsProj.Args) {
this.license = license;
this.githubUrl = githubUrl;
this.context = context;
Expand Down Expand Up @@ -585,8 +579,8 @@ ${this.getAdditionalItemGroups().join(`\n${FOUR_SPACES}`)}

private getPropertyGroups(): string[] {
const result: string[] = [];
if (this.version != null) {
result.push(`<Version>${this.version}</Version>`);
if (this.context.version != null) {
result.push(`<Version>${this.context.version}</Version>`);
}

result.push("<PackageReadmeFile>README.md</PackageReadmeFile>");
Expand Down
2 changes: 1 addition & 1 deletion generators/csharp/model/src/version/VersionGenerator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export class VersionGenerator extends FileGenerator<CSharpFile, ModelCustomConfi
type: csharp.Type.string(),
access: "public",
const_: true,
initializer: csharp.codeblock(`"${this.context.getVersion() ?? DEFAULT_VERSION}"`)
initializer: csharp.codeblock(`"${this.context.version ?? DEFAULT_VERSION}"`)
})
);

Expand Down
10 changes: 10 additions & 0 deletions generators/php/codegen/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,19 @@
"organize-imports": "organize-imports-cli tsconfig.json",
"depcheck": "depcheck"
},
"dependencies": {
"@fern-api/fs-utils": "workspace:*",
"@fern-api/generator-commons": "workspace:*",
"@fern-api/logging-execa": "workspace:*",
"@fern-fern/ir-sdk": "^53.7.0",
"lodash-es": "^4.17.21",
"zod": "^3.22.3"
},
"devDependencies": {
"@fern-api/fs-utils": "workspace:*",
"@fern-api/generator-commons": "workspace:*",
"@fern-api/logging-execa": "workspace:*",
"@types/lodash-es": "^4.17.12",
"@fern-fern/ir-sdk": "^53.7.0",
"zod": "^3.22.3",
"@types/jest": "^29.5.12",
Expand Down
9 changes: 8 additions & 1 deletion generators/php/codegen/src/AsIs.ts
Original file line number Diff line number Diff line change
@@ -1 +1,8 @@
export enum AsIsFiles {}
export enum AsIsFiles {
GitIgnore = ".gitignore",
GithubCiYml = "github-ci.yml",
PhpStanNeon = "phpstan.neon",
PhpUnitXml = "phpunit.xml",
RawClient = "RawClient.Template.php",
RawClientTest = "RawClientTest.Template.php"
}
2 changes: 1 addition & 1 deletion generators/php/codegen/src/FileGenerator.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { RelativeFilePath } from "@fern-api/fs-utils";
import { AbstractPhpGeneratorContext } from "./context/AbstractPhpGeneratorContext";
import { BasePhpCustomConfigSchema } from "./custom-config/BasePhpCustomConfigSchema";
import { File } from "./project/File";
import { File } from "@fern-api/generator-commons";

export abstract class FileGenerator<
GeneratedFile extends File,
Expand Down
4 changes: 4 additions & 0 deletions generators/php/codegen/src/asIs/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
.php-cs-fixer.cache
.phpunit.result.cache
composer.lock
vendor/
11 changes: 11 additions & 0 deletions generators/php/codegen/src/asIs/RawClient.Template.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

namespace <%= namespace%>;

class RawClient
{
public function __construct()
{
// TODO: Implement me!
}
}
13 changes: 13 additions & 0 deletions generators/php/codegen/src/asIs/RawClientTest.Template.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

namespace <%= namespace%>;

use PHPUnit\Framework\TestCase;

class RawClientTest extends TestCase
{
public function testRawClient()
{
$this->assertTrue(true);
}
}
46 changes: 46 additions & 0 deletions generators/php/codegen/src/asIs/github-ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
name: ci

on: [push]

jobs:
compile:
runs-on: ubuntu-latest

steps:
- name: Checkout repo
uses: actions/checkout@v4

- name: Setup Composer
uses: php-actions/composer@v6
with:
php_version: "8.1"
version: "2.7.9"

- name: Install tools
run: |
composer install
- name: Build
run: |
composer build
unit-tests:
runs-on: ubuntu-latest

steps:
- name: Checkout repo
uses: actions/checkout@v4

- name: Setup Composer
uses: php-actions/composer@v6
with:
php_version: "8.1"
version: "2.7.9"

- name: Install tools
run: |
composer install
- name: Run Tests
run: |
composer test
5 changes: 5 additions & 0 deletions generators/php/codegen/src/asIs/phpstan.neon
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
parameters:
level: max
paths:
- src
- tests
7 changes: 7 additions & 0 deletions generators/php/codegen/src/asIs/phpunit.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<phpunit bootstrap="vendor/autoload.php">
<testsuites>
<testsuite name="Test Suite">
<directory suffix="Test.php">tests</directory>
</testsuite>
</testsuites>
</phpunit>
2 changes: 1 addition & 1 deletion generators/php/codegen/src/cli/AbstractPhpGeneratorCli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export abstract class AbstractPhpGeneratorCli<
CsharpGeneratorContext extends AbstractPhpGeneratorContext<CustomConfig>
> extends AbstractGeneratorCli<CustomConfig, IntermediateRepresentation, CsharpGeneratorContext> {
/**
* Parses the IR for the Csharp generators
* Parses the IR for the PHP generators
* @param irFilepath
* @returns
*/
Expand Down
32 changes: 32 additions & 0 deletions generators/php/codegen/src/context/AbstractPhpGeneratorContext.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,48 @@
import { AbstractGeneratorContext, FernGeneratorExec, GeneratorNotificationService } from "@fern-api/generator-commons";
import { IntermediateRepresentation } from "@fern-fern/ir-sdk/api";
import { BasePhpCustomConfigSchema } from "../custom-config/BasePhpCustomConfigSchema";
import { PhpProject } from "../project";
import { camelCase, upperFirst } from "lodash-es";

export abstract class AbstractPhpGeneratorContext<
CustomConfig extends BasePhpCustomConfigSchema
> extends AbstractGeneratorContext {
private namespace: string;
public readonly project: PhpProject;

public constructor(
public readonly ir: IntermediateRepresentation,
public readonly config: FernGeneratorExec.config.GeneratorConfig,
public readonly customConfig: CustomConfig,
public readonly generatorNotificationService: GeneratorNotificationService
) {
super(config, generatorNotificationService);
this.namespace = this.customConfig.namespace ?? upperFirst(camelCase(`${this.config.organization}`));
this.project = new PhpProject({
context: this,
name: this.namespace
});
}

public getNamespace(): string {
return this.namespace;
}

public getTestsNamespace(): string {
return `${this.namespace}\\Tests`;
}

public getCoreNamespace(): string {
return `${this.namespace}\\Core`;
}

public getCoreTestsNamespace(): string {
return `${this.namespace}\\Core\\Tests`;
}

public abstract getRawAsIsFiles(): string[];

public abstract getCoreAsIsFiles(): string[];

public abstract getCoreTestAsIsFiles(): string[];
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { z } from "zod";

export const BasePhpCustomConfigSchema = z.object({});
export const BasePhpCustomConfigSchema = z.object({
namespace: z.string().optional()
});

export type BasePhpCustomConfigSchema = z.infer<typeof BasePhpCustomConfigSchema>;
1 change: 1 addition & 0 deletions generators/php/codegen/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@ export * from "./AsIs";
export { AbstractPhpGeneratorContext } from "./context/AbstractPhpGeneratorContext";
export { AbstractPhpGeneratorCli } from "./cli/AbstractPhpGeneratorCli";
export { BasePhpCustomConfigSchema } from "./custom-config/BasePhpCustomConfigSchema";
export { PhpFile } from "./project/PhpFile";
export * as php from "./php";
Loading

0 comments on commit 63d33bb

Please sign in to comment.