Skip to content

Commit ff0f7cf

Browse files
fix(gatsby-plugin-netlify): Fix heuristic for appending redirects (#23743)
1 parent 4b0e2dd commit ff0f7cf

File tree

1 file changed

+16
-11
lines changed

1 file changed

+16
-11
lines changed

Diff for: packages/gatsby-plugin-netlify/src/create-redirects.js

+16-11
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { HEADER_COMMENT } from "./constants"
2-
import { appendFile, exists, readFile, writeFile } from "fs-extra"
2+
import { exists, readFile, writeFile } from "fs-extra"
33

44
export default async function writeRedirectsFile(
55
pluginData,
@@ -54,22 +54,27 @@ export default async function writeRedirectsFile(
5454
({ fromPath, toPath }) => `${fromPath} ${toPath} 200`
5555
)
5656

57-
let appendToFile = false
57+
let commentFound = false
5858

5959
// Websites may also have statically defined redirects
6060
// In that case we should append to them (not overwrite)
6161
// Make sure we aren't just looking at previous build results though
6262
const fileExists = await exists(FILE_PATH)
63+
let fileContents = ``
6364
if (fileExists) {
64-
const fileContents = await readFile(FILE_PATH)
65-
if (fileContents.indexOf(HEADER_COMMENT) < 0) {
66-
appendToFile = true
67-
}
65+
fileContents = await readFile(FILE_PATH, `utf8`)
66+
commentFound = fileContents.includes(HEADER_COMMENT)
67+
}
68+
let data
69+
if (commentFound) {
70+
const [theirs] = fileContents.split(`\n${HEADER_COMMENT}\n`)
71+
data = theirs
72+
} else {
73+
data = fileContents
6874
}
6975

70-
const data = `${HEADER_COMMENT}\n\n${[...redirects, ...rewrites].join(`\n`)}`
71-
72-
return appendToFile
73-
? appendFile(FILE_PATH, `\n\n${data}`)
74-
: writeFile(FILE_PATH, data)
76+
return writeFile(
77+
FILE_PATH,
78+
[data, HEADER_COMMENT, ...redirects, ...rewrites].join(`\n`)
79+
)
7580
}

0 commit comments

Comments
 (0)