Skip to content

gitignore .apphosting/ #377

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 11 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
106 changes: 106 additions & 0 deletions packages/@apphosting/adapter-nextjs/src/bin/build.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,112 @@ outputFiles:
async () => await validateOutputDirectory(outputBundleOptions, path.join(tmpDir, ".next")),
);
});
it(".apphosting gitignored correctly in a monorepo setup", async () => {
const { generateBuildOutput } = await importUtils;
const files = {
".next/standalone/apps/next-app/standalonefile": "",
".next/static/staticfile": "",
};
generateTestFiles(tmpDir, files);
await generateBuildOutput(
tmpDir,
"apps/next-app",
{
bundleYamlPath: path.join(tmpDir, ".apphosting", "bundle.yaml"),
outputDirectoryBasePath: path.join(tmpDir, ".apphosting"),
outputDirectoryAppPath: path.join(tmpDir, ".next", "standalone", "apps", "next-app"),
outputPublicDirectoryPath: path.join(
tmpDir,
".next",
"standalone",
"apps",
"next-app",
"public",
),
outputStaticDirectoryPath: path.join(
tmpDir,
".next",
"standalone",
"apps",
"next-app",
".next",
"static",
),
serverFilePath: path.join(tmpDir, ".next", "standalone", "apps", "next-app", "server.js"),
},
path.join(tmpDir, ".next"),
defaultNextVersion,
adapterMetadata,
);

const expectedFiles = {
".gitignore": "/.apphosting/",
};
const expectedPartialYaml = {
version: "v1",
runConfig: { runCommand: "node .next/standalone/apps/next-app/server.js" },
};
validateTestFiles(tmpDir, expectedFiles);
validatePartialYamlContents(tmpDir, ".apphosting/bundle.yaml", expectedPartialYaml);
});

it(".apphosting gitignored without existing .gitignore file", async () => {
const { generateBuildOutput, validateOutputDirectory } = await importUtils;
const files = {
// .next/standalone/.next/ must be created beforehand otherwise
// generateBuildOutput will attempt to copy
// .next/ into .next/standalone/.next
".next/standalone/.next/package.json": "",
".next/static/staticfile": "",
};
generateTestFiles(tmpDir, files);
await generateBuildOutput(
tmpDir,
tmpDir,
outputBundleOptions,
path.join(tmpDir, ".next"),
defaultNextVersion,
{
adapterPackageName: "@apphosting/adapter-nextjs",
adapterVersion: "14.0.1",
},
);
await validateOutputDirectory(outputBundleOptions, path.join(tmpDir, ".next"));

const expectedFiles = {
".gitignore": "/.apphosting/",
};
validateTestFiles(tmpDir, expectedFiles);
});
it(".apphosting gitignored in existing .gitignore file", async () => {
const { generateBuildOutput, validateOutputDirectory } = await importUtils;
const files = {
// .next/standalone/.next/ must be created beforehand otherwise
// generateBuildOutput will attempt to copy
// .next/ into .next/standalone/.next
".next/standalone/.next/package.json": "",
".next/static/staticfile": "",
".gitignore": "/.next/",
};
generateTestFiles(tmpDir, files);
await generateBuildOutput(
tmpDir,
tmpDir,
outputBundleOptions,
path.join(tmpDir, ".next"),
defaultNextVersion,
{
adapterPackageName: "@apphosting/adapter-nextjs",
adapterVersion: "14.0.1",
},
);
await validateOutputDirectory(outputBundleOptions, path.join(tmpDir, ".next"));

const expectedFiles = {
".gitignore": "/.next/\n/.apphosting/",
};
validateTestFiles(tmpDir, expectedFiles);
});
Comment on lines +216 to +272

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

These two tests (.apphosting gitignored without existing .gitignore file and .apphosting gitignored in existing .gitignore file) contain a lot of duplicated setup and execution logic. To improve maintainability and reduce redundancy, consider refactoring them into a single parameterized test. You can create an array of test cases and iterate over it, which will make the test suite cleaner and easier to extend in the future.

  [
    {
      description: "without existing .gitignore file",
      initialFiles: {
        ".next/standalone/.next/package.json": "",
        ".next/static/staticfile": "",
      },
      expectedGitignore: "/.apphosting/",
    },
    {
      description: "in existing .gitignore file",
      initialFiles: {
        ".next/standalone/.next/package.json": "",
        ".next/static/staticfile": "",
        ".gitignore": "/.next/",
      },
      expectedGitignore: "/.next/\n/.apphosting/",
    },
  ].forEach(({ description, initialFiles, expectedGitignore }) => {
    it(`.apphosting gitignored ${description}`, async () => {
      const { generateBuildOutput, validateOutputDirectory } = await importUtils;
      generateTestFiles(tmpDir, initialFiles);
      await generateBuildOutput(
        tmpDir,
        tmpDir,
        outputBundleOptions,
        path.join(tmpDir, ".next"),
        defaultNextVersion,
        {
          adapterPackageName: "@apphosting/adapter-nextjs",
          adapterVersion: "14.0.1",
        },
      );
      await validateOutputDirectory(outputBundleOptions, path.join(tmpDir, ".next"));

      const expectedFiles = {
        ".gitignore": expectedGitignore,
      };
      validateTestFiles(tmpDir, expectedFiles);
    });
  });

it("expects directories and other files to be copied over", async () => {
const { generateBuildOutput, validateOutputDirectory } = await importUtils;
const files = {
Expand Down
8 changes: 5 additions & 3 deletions packages/@apphosting/adapter-nextjs/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@ import {
MiddlewareManifest,
} from "./interfaces.js";
import { NextConfigComplete } from "next/dist/server/config-shared.js";
import { OutputBundleConfig } from "@apphosting/common";
import { OutputBundleConfig, updateOrCreateGitignore } from "@apphosting/common";

// fs-extra is CJS, readJson can't be imported using shorthand
export const { copy, exists, writeFile, readJson, readdir, readFileSync, existsSync, mkdir } =
export const { copy, exists, writeFile, readJson, readdir, readFileSync, existsSync, ensureDir } =
fsExtra;

// Loads the user's next.config.js file.
Expand Down Expand Up @@ -181,7 +181,7 @@ async function generateBundleYaml(
nextVersion: string,
adapterMetadata: AdapterMetadata,
): Promise<void> {
await mkdir(opts.outputDirectoryBasePath);
await ensureDir(opts.outputDirectoryBasePath);
const outputBundle: OutputBundleConfig = {
version: "v1",
runConfig: {
Expand All @@ -203,6 +203,8 @@ async function generateBundleYaml(
}

await writeFile(opts.bundleYamlPath, yamlStringify(outputBundle));
const normalizedBundleDir = normalize(relative(cwd, opts.outputDirectoryBasePath));
updateOrCreateGitignore(cwd, [`/${normalizedBundleDir}/`]);
return;
}

Expand Down
3 changes: 2 additions & 1 deletion packages/@apphosting/common/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@apphosting/common",
"version": "0.0.5",
"version": "0.0.6",
"description": "Shared library code for App Hosting framework adapters",
"author": {
"name": "Firebase",
Expand All @@ -17,6 +17,7 @@
},
"scripts": {
"build": "tsc",
"test": "ts-mocha -p tsconfig.json 'src/**/*.spec.ts' 'src/*.spec.ts'",
"localregistry:start": "npx verdaccio --config ../publish-dev/verdaccio-config.yaml",
"localregistry:publish": "(npm view --registry=http://localhost:4873 @apphosting/common && npm unpublish --@apphosting:registry=http://localhost:4873 --force); npm publish --@apphosting:registry=http://localhost:4873"
},
Expand Down
30 changes: 30 additions & 0 deletions packages/@apphosting/common/src/index.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import assert from "assert";
import fs from "fs";
import path from "path";
import os from "os";
import { updateOrCreateGitignore } from "./index";

describe("update or create .gitignore", () => {
let tmpDir: string;
beforeEach(() => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "test-gitignore"));
});

afterEach(() => {
fs.rmSync(tmpDir, { recursive: true, force: true });
});

it(".gitignore file exists and is correctly updated with missing paths", () => {
fs.writeFileSync(path.join(tmpDir, ".gitignore"), "existingpath/");

updateOrCreateGitignore(tmpDir, ["existingpath/", "newpath/"]);

const gitignoreContent = fs.readFileSync(path.join(tmpDir, ".gitignore"), "utf-8");
assert.equal(`existingpath/\nnewpath/`, gitignoreContent);
});
it(".gitignore file does not exist and is created", () => {
updateOrCreateGitignore(tmpDir, ["chickenpath/", "newpath/"]);
const gitignoreContent = fs.readFileSync(path.join(tmpDir, ".gitignore"), "utf-8");
assert.equal(`chickenpath/\nnewpath/`, gitignoreContent);
});
});
25 changes: 25 additions & 0 deletions packages/@apphosting/common/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { spawn } from "child_process";
import * as fs from "node:fs";
import * as path from "node:path";

// Output bundle metadata specifications to be written to bundle.yaml
export interface OutputBundleConfig {
Expand Down Expand Up @@ -139,3 +141,26 @@ export function getBuildOptions(): BuildOptions {
projectDirectory: process.cwd(),
};
}

/**
* Updates or creates a .gitignore file with the given entries in the given path
*/
export function updateOrCreateGitignore(dirPath: string, entries: string[]) {
const gitignorePath = path.join(dirPath, ".gitignore");

if (!fs.existsSync(gitignorePath)) {
console.log(`creating ${gitignorePath} with entries: ${entries.join("\n")}`);
fs.writeFileSync(gitignorePath, entries.join("\n"));
return;
}

let content = fs.readFileSync(gitignorePath, "utf-8");
for (const entry of entries) {
if (!content.split("\n").includes(entry)) {
console.log(`adding ${entry} to ${gitignorePath}`);
content += `\n${entry}`;
}
}

fs.writeFileSync(gitignorePath, content);
Comment on lines +157 to +165

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

This implementation re-splits the file content on every iteration of the loop, which can be inefficient. Also, the way new entries are appended with \n${entry} can lead to an initial newline if the file is empty.

A more robust and performant approach would be to read the existing entries into a Set once, filter out the entries that already exist, and then append the new entries with proper newline handling.

  let content = fs.readFileSync(gitignorePath, "utf-8");
  const existingEntries = new Set(content.split("\n"));

  const entriesToAdd = entries.filter(entry => !existingEntries.has(entry));

  if (entriesToAdd.length > 0) {
    entriesToAdd.forEach(entry => console.log(`adding ${entry} to ${gitignorePath}`));

    if (content.length > 0 && !content.endsWith("\n")) {
      content += "\n";
    }

    content += entriesToAdd.join("\n");
    fs.writeFileSync(gitignorePath, content);
  }

}