Skip to content
This repository was archived by the owner on May 10, 2021. It is now read-only.

Commit 9d78777

Browse files
committed
some cleanup and extra test case
1 parent bd66d46 commit 9d78777

File tree

5 files changed

+115
-99
lines changed

5 files changed

+115
-99
lines changed

lib/helpers/handleFileTracking.js

+80
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
const { join } = require("path");
2+
const {
3+
existsSync,
4+
readdirSync,
5+
readFileSync,
6+
writeFileSync,
7+
removeSync,
8+
} = require("fs-extra");
9+
const findCacheDir = require("find-cache-dir");
10+
const { NETLIFY_PUBLISH_PATH, NETLIFY_FUNCTIONS_PATH } = require("../config");
11+
12+
const TRACKING_FILE_SEPARATOR = "---";
13+
14+
// Clean configured publish and functions folders and track next-on-netlify files
15+
// for future cleans
16+
const handleFileTracking = ({ functionsPath, publishPath }) => {
17+
const isConfiguredFunctionsDir = functionsPath !== NETLIFY_FUNCTIONS_PATH;
18+
const isConfiguredPublishDir = publishPath !== NETLIFY_PUBLISH_PATH;
19+
20+
const cacheDir = findCacheDir({ name: "next-on-netlify", create: true });
21+
const trackingFilePath = join(cacheDir, ".nonfiletracking");
22+
23+
if (existsSync(trackingFilePath)) {
24+
const trackingFile = readFileSync(trackingFilePath, "utf8");
25+
const [trackedFunctions, trackedPublish] = trackingFile.split(
26+
TRACKING_FILE_SEPARATOR
27+
);
28+
29+
const cleanConfiguredFiles = (trackedFiles) => {
30+
trackedFiles.forEach((file) => {
31+
const filePath = join(publishPath, file);
32+
if (file !== "" && existsSync(filePath)) {
33+
removeSync(filePath);
34+
}
35+
});
36+
};
37+
38+
if (isConfiguredPublishDir) {
39+
cleanConfiguredFiles(trackedPublish.split("\n"));
40+
}
41+
if (isConfiguredFunctionsDir) {
42+
cleanConfiguredFiles(trackedFunctions.split("\n"));
43+
}
44+
}
45+
46+
const functionsBeforeRun = existsSync(functionsPath)
47+
? readdirSync(functionsPath)
48+
: [];
49+
const publishBeforeRun = existsSync(publishPath)
50+
? readdirSync(publishPath)
51+
: [];
52+
53+
// this callback will run at the end of nextOnNetlify()
54+
const trackNewFiles = () => {
55+
const functionsAfterRun = isConfiguredFunctionsDir
56+
? readdirSync(functionsPath)
57+
: functionsBeforeRun;
58+
const publishAfterRun = isConfiguredPublishDir
59+
? readdirSync(publishPath)
60+
: publishBeforeRun;
61+
const getDifference = (before, after) =>
62+
after.filter((filePath) => !before.includes(filePath));
63+
const newFunctionsFiles = getDifference(
64+
functionsBeforeRun,
65+
functionsAfterRun
66+
);
67+
const newPublishFiles = getDifference(publishBeforeRun, publishAfterRun);
68+
69+
const allTrackedFiles = [
70+
...newFunctionsFiles,
71+
TRACKING_FILE_SEPARATOR,
72+
...newPublishFiles,
73+
];
74+
writeFileSync(trackingFilePath, allTrackedFiles.join("\n"));
75+
};
76+
77+
return trackNewFiles;
78+
};
79+
80+
module.exports = handleFileTracking;

lib/steps/prepareFolders.js

+13-71
Original file line numberDiff line numberDiff line change
@@ -1,95 +1,37 @@
11
const { join } = require("path");
2-
const {
3-
emptyDirSync,
4-
existsSync,
5-
readdirSync,
6-
readFileSync,
7-
writeFileSync,
8-
removeSync,
9-
} = require("fs-extra");
2+
const { emptyDirSync } = require("fs-extra");
103
const findCacheDir = require("find-cache-dir");
114
const { logTitle, log } = require("../helpers/logger");
125
const { NETLIFY_PUBLISH_PATH, NETLIFY_FUNCTIONS_PATH } = require("../config");
13-
14-
const TRACKING_FILE_SEPARATOR = "---";
6+
const handleFileTracking = require("../helpers/handleFileTracking");
157

168
// Clean existing publish and functions folders
179
const prepareFolders = ({ functionsPath, publishPath }) => {
1810
logTitle("🚀 Next on Netlify 🚀");
1911

20-
if (functionsPath === NETLIFY_FUNCTIONS_PATH) {
12+
const isNotConfiguredFunctionsDir = functionsPath === NETLIFY_FUNCTIONS_PATH;
13+
const isNotConfiguredPublishDir = publishPath === NETLIFY_PUBLISH_PATH;
14+
15+
if (isNotConfiguredFunctionsDir) {
2116
log(" ", "Functions directory: ", functionsPath);
2217
}
23-
if (publishPath === NETLIFY_PUBLISH_PATH) {
18+
if (isNotConfiguredPublishDir) {
2419
log(" ", "Publish directory: ", publishPath);
2520
}
26-
if (
27-
functionsPath === NETLIFY_FUNCTIONS_PATH ||
28-
publishPath === NETLIFY_PUBLISH_PATH
29-
) {
21+
if (isNotConfiguredFunctionsDir || isNotConfiguredPublishDir) {
3022
log(" ", "Make sure these are set in your netlify.toml file.");
3123
}
3224

33-
const cacheDir = findCacheDir({ name: "next-on-netlify", create: true });
34-
const trackingFilePath = join(cacheDir, ".nonfiletracking");
35-
const trackingFile = existsSync(trackingFilePath)
36-
? readFileSync(trackingFilePath, "utf8")
37-
: "---";
38-
39-
const [trackedFunctions, trackedPublish] = trackingFile.split("---");
40-
const isConfiguredPublishDir = publishPath !== NETLIFY_PUBLISH_PATH;
41-
const isConfiguredFunctionsDir = functionsPath !== NETLIFY_FUNCTIONS_PATH;
42-
43-
if (isConfiguredPublishDir) {
44-
trackedPublish
45-
.trim()
46-
.split("\n")
47-
.forEach((file) => {
48-
const filePath = join(publishPath, file);
49-
if (existsSync(filePath) && file !== "") {
50-
removeSync(filePath);
51-
}
52-
});
53-
} else {
25+
// We can empty these dirs knowing there will only be stale NoN-generated files inside
26+
if (isNotConfiguredPublishDir) {
5427
emptyDirSync(publishPath);
5528
}
56-
if (isConfiguredFunctionsDir) {
57-
trackedFunctions
58-
.trim()
59-
.split("\n")
60-
.forEach((file) => {
61-
const filePath = join(functionsPath, file);
62-
if (existsSync(filePath) && file !== "") {
63-
removeSync(filePath);
64-
}
65-
});
66-
} else {
29+
if (isNotConfiguredFunctionsDir) {
6730
emptyDirSync(functionsPath);
6831
}
6932

70-
const functionsBeforeRun = existsSync(functionsPath)
71-
? readdirSync(functionsPath)
72-
: [];
73-
const publishBeforeRun = existsSync(publishPath)
74-
? readdirSync(publishPath)
75-
: [];
76-
77-
// this callback will run at the end of nextOnNetlify()
78-
return () => {
79-
const functionsAfterRun = isConfiguredFunctionsDir
80-
? readdirSync(functionsPath)
81-
: functionsBeforeRun;
82-
const publishAfterRun = isConfiguredPublishDir
83-
? readdirSync(publishPath)
84-
: publishBeforeRun;
85-
const getDiff = (before, after) =>
86-
after.filter((filePath) => !before.includes(filePath));
87-
const functionsDiff = getDiff(functionsBeforeRun, functionsAfterRun);
88-
const publishDiff = getDiff(publishBeforeRun, publishAfterRun);
89-
90-
const totalFilesDiff = [...functionsDiff, "---", ...publishDiff];
91-
writeFileSync(trackingFilePath, totalFilesDiff.join("\n"));
92-
};
33+
// This returns a function that runs as the last step of nextOnNetlify()
34+
return handleFileTracking({ functionsPath, publishPath });
9335
};
9436

9537
module.exports = prepareFolders;

tests/configurableDirs.test.js

+8-2
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ beforeAll(
2525
.withPages("pages")
2626
.withNextConfig("next.config.js")
2727
.withPackageJson("package.json")
28+
.withCustomFunctions("my-functions")
2829
.runWithRequire({ functionsDir: FUNCTIONS_DIR, publishDir: PUBLISH_DIR });
2930
},
3031
// time out after 180 seconds
@@ -38,6 +39,10 @@ describe("next-on-netlify", () => {
3839
expect(runOutput).toMatch("Built successfully!");
3940
});
4041

42+
test("copies custom Netlify Function to configured functions directory", () => {
43+
expect(existsSync(join(functionsDir, "someTestFunction.js"))).toBe(true);
44+
});
45+
4146
test("creates a Netlify Function for each SSR page", () => {
4247
expect(existsSync(join(functionsDir, "next_index", "next_index.js"))).toBe(
4348
true
@@ -125,8 +130,9 @@ describe("clean up of NoN files", () => {
125130
"next_shows_id",
126131
"next_shows_params",
127132
];
128-
const fileListFunctions = fileList.split("---")[0].trim().split("\n");
133+
const fileListFunctions = fileList.split("---")[0].split("\n");
129134
expect(isSameList(nextFunctions, fileListFunctions)).toBe(true);
135+
expect(fileListFunctions.includes("someTestFunction.js")).toBe(false);
130136
const publishFiles = [
131137
"404.html",
132138
"_next",
@@ -135,7 +141,7 @@ describe("clean up of NoN files", () => {
135141
"static",
136142
"static.html",
137143
];
138-
const fileListPublish = fileList.split("---")[1].trim().split("\n");
144+
const fileListPublish = fileList.split("---")[1].split("\n");
139145
expect(isSameList(publishFiles, fileListPublish)).toBe(true);
140146
});
141147
});

tests/fixtures/my-functions/someTestFunction.js

Whitespace-only changes.

tests/helpers/buildNextApp.js

+14-26
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,10 @@ class NextAppBuilder {
4646
return this.withFile(packageJsonFile, "package.json");
4747
}
4848

49+
withCustomFunctions(functionsDir) {
50+
return this.withFile(functionsDir);
51+
}
52+
4953
// Copy a file from the fixtures folder to the app's staging folder
5054
withFile(fixture, target = null) {
5155
// If no target file name is given, use the same name as the fixture
@@ -61,8 +65,7 @@ class NextAppBuilder {
6165
return this;
6266
}
6367

64-
// Build the application with next build
65-
async build() {
68+
async buildNextApp() {
6669
// Generate a cache hash ID from the current contents of the staging folder.
6770
const { hash: cacheHash } = await hashElement(this.__stagingPath, {
6871
encoding: "hex",
@@ -83,33 +86,21 @@ class NextAppBuilder {
8386
// run next-on-netlify
8487
copySync(this.__cachePath, this.__appPath);
8588

86-
// Run next-on-netlify
89+
process.chdir(this.__appPath);
90+
}
91+
92+
async build() {
93+
await this.buildNextApp();
94+
95+
// Run next-on-netlify as postbuild script
8796
const { stdout } = await npmRun("next-on-netlify", this.__appPath);
8897
return stdout;
8998
}
9099

91100
async runWithRequire(options) {
92-
// Generate a cach hash ID from the current contents of the staging folder.
93-
const { hash: cacheHash } = await hashElement(this.__stagingPath, {
94-
encoding: "hex",
95-
});
96-
this.__cacheHash = cacheHash;
97-
98-
// If we have no cached build for this NextJS app, let's run next build and
99-
// cache the result
100-
if (!existsSync(this.__cachePath)) {
101-
// Build the nextJS app
102-
await npmRun("next-build", this.__stagingPath);
103-
104-
// Cache the build
105-
copySync(this.__stagingPath, this.__cachePath);
106-
}
101+
await this.buildNextApp();
107102

108-
// Copy the built NextJS app from the cache to the app folder, where we will
109-
// run next-on-netlify
110-
copySync(this.__cachePath, this.__appPath);
111-
112-
process.chdir(this.__appPath);
103+
// Run next-on-netlify as an imported module
113104
const nextOnNetlify = require("../..");
114105
nextOnNetlify({
115106
functionsDir: join(this.__appPath, options.functionsDir),
@@ -118,9 +109,6 @@ class NextAppBuilder {
118109
return "Built successfully!";
119110
}
120111

121-
// TO-DO: when I try to split out the shared logic between build & runWithRequire into its own
122-
// function on NextBuilder, everything breaks; not sure why
123-
124112
/*****************************************************************************
125113
* Private functions
126114
****************************************************************************/

0 commit comments

Comments
 (0)