MCPcopy Index your code
hub / github.com/ember-cli/ember-cli / insertIntoFile

Function insertIntoFile

lib/utilities/insert-into-file.js:50–123  ·  view source on GitHub ↗

Inserts the given content into a file. If the `contentsToInsert` string is already present in the current contents, the file will not be changed unless `force` option is passed. If `options.before` is specified, `contentsToInsert` will be inserted before the first instance of that string.

(fullPath, contentsToInsert, providedOptions)

Source from the content-addressed store, hash-verified

48 @return {Promise}
49*/
50async function insertIntoFile(fullPath, contentsToInsert, providedOptions) {
51 let options = providedOptions || {};
52
53 let returnValue = {
54 path: fullPath,
55 originalContents: '',
56 contents: '',
57 inserted: false,
58 };
59
60 let exists = fs.existsSync(fullPath);
61
62 if (exists || (!exists && options.create !== false)) {
63 let originalContents = '';
64
65 if (exists) {
66 originalContents = fs.readFileSync(fullPath, { encoding: 'utf8' });
67 }
68
69 let contentsToWrite = originalContents;
70
71 let alreadyPresent = originalContents.indexOf(contentsToInsert) > -1;
72 let insert = !alreadyPresent;
73 let insertBehavior = 'end';
74
75 if (options.before) {
76 insertBehavior = 'before';
77 }
78 if (options.after) {
79 insertBehavior = 'after';
80 }
81
82 if (options.force) {
83 insert = true;
84 }
85
86 if (insert) {
87 if (insertBehavior === 'end') {
88 contentsToWrite += contentsToInsert;
89 } else {
90 let contentMarker = options[insertBehavior];
91 if (contentMarker instanceof RegExp) {
92 let matches = contentsToWrite.match(contentMarker);
93 if (matches) {
94 contentMarker = matches[0];
95 }
96 }
97 let contentMarkerIndex = contentsToWrite.indexOf(contentMarker);
98
99 if (contentMarkerIndex !== -1) {
100 let insertIndex = contentMarkerIndex;
101 if (insertBehavior === 'after') {
102 insertIndex += contentMarker.length;
103 }
104
105 contentsToWrite =
106 contentsToWrite.slice(0, insertIndex) + contentsToInsert + EOL + contentsToWrite.slice(insertIndex);
107 }

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…