|
1 | 1 | import { HEADER_COMMENT } from "./constants"
|
2 |
| -import { appendFile, exists, readFile, writeFile } from "fs-extra" |
| 2 | +import { exists, readFile, writeFile } from "fs-extra" |
3 | 3 |
|
4 | 4 | export default async function writeRedirectsFile(
|
5 | 5 | pluginData,
|
@@ -54,22 +54,27 @@ export default async function writeRedirectsFile(
|
54 | 54 | ({ fromPath, toPath }) => `${fromPath} ${toPath} 200`
|
55 | 55 | )
|
56 | 56 |
|
57 |
| - let appendToFile = false |
| 57 | + let commentFound = false |
58 | 58 |
|
59 | 59 | // Websites may also have statically defined redirects
|
60 | 60 | // In that case we should append to them (not overwrite)
|
61 | 61 | // Make sure we aren't just looking at previous build results though
|
62 | 62 | const fileExists = await exists(FILE_PATH)
|
| 63 | + let fileContents = `` |
63 | 64 | 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 |
68 | 74 | }
|
69 | 75 |
|
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 | + ) |
75 | 80 | }
|
0 commit comments