MCPcopy Create free account
hub / github.com/vercel/vercel / writeGoMod

Function writeGoMod

packages/go/src/index.ts:761–825  ·  view source on GitHub ↗

* Writes a `go.mod` file in the specified directory. If a `go.mod` file * exists, then update the module name and any relative `replace` statements, * otherwise write the minimum module name. * @param workPath The work path; required if `goModPath` exists * @param goModPath The path to the `go.m

({
  destDir,
  goModPath,
  packageName,
}: {
  destDir: string;
  goModPath?: string;
  packageName: string;
})

Source from the content-addressed store, hash-verified

759 * @param packageName The module name to inject into the `go.mod`
760 */
761async function writeGoMod({
762 destDir,
763 goModPath,
764 packageName,
765}: {
766 destDir: string;
767 goModPath?: string;
768 packageName: string;
769}) {
770 let contents = `module ${packageName}`;
771
772 if (goModPath) {
773 const goModRelPath = relative(destDir, dirname(goModPath));
774 const goModContents = await readFile(goModPath, 'utf-8');
775
776 contents = goModContents
777 .replace(/^module\s+.+$/m, contents)
778 .replace(
779 /^(replace .+=>\s*)(.+)$/gm,
780 (orig, replaceStmt, replacePath) => {
781 if (replacePath.startsWith('.')) {
782 let newPath = join(goModRelPath, replacePath);
783 // path.join() strips the './' prefix when goModRelPath is
784 // empty. Go requires replacement paths without a version to
785 // start with './' or '../', so restore the prefix when needed.
786 if (!newPath.startsWith('.') && !newPath.startsWith('/')) {
787 newPath = './' + newPath;
788 }
789 return replaceStmt + newPath;
790 }
791 return orig;
792 }
793 );
794
795 // get the module name, then add the 'replace' mapping if it doesn't
796 // already exist
797 const matches = goModContents.match(/module\s+(.+)/);
798 const moduleName = matches ? matches[1] : null;
799 if (moduleName) {
800 let relPath = normalize(goModRelPath);
801 if (!relPath.endsWith('/')) {
802 relPath += '/';
803 }
804
805 const requireRE = new RegExp(`require\\s+${moduleName}`);
806 const requireGroupRE = new RegExp(
807 `require\\s*\\(.*${moduleName}.*\\)`,
808 's'
809 );
810 if (!requireRE.test(contents) && !requireGroupRE.test(contents)) {
811 contents += `require ${moduleName} v0.0.0-unpublished\n`;
812 }
813
814 const replaceRE = new RegExp(`replace.+=>\\s+${relPath}(\\s|$)`);
815 if (!replaceRE.test(contents)) {
816 contents += `replace ${moduleName} => ${relPath}\n`;
817 }
818 }

Callers 2

buildHandlerWithGoModFunction · 0.85
startDevServerFunction · 0.85

Calls 7

relativeFunction · 0.90
debugFunction · 0.90
normalizeFunction · 0.85
replaceMethod · 0.80
testMethod · 0.80
readFileFunction · 0.50
matchMethod · 0.45

Tested by

no test coverage detected