@vercel/go 2.0.11 → 2.0.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +331 -263
  2. package/package.json +5 -6
package/dist/index.js CHANGED
@@ -17720,315 +17720,383 @@ async function initPrivateGit(credentials) {
17720
17720
  * which works great for this feature. We also need to add a suffix during `vercel dev`
17721
17721
  * since the entrypoint is already stripped of its suffix before build() is called.
17722
17722
  */
17723
- async function getRenamedEntrypoint(entrypoint, files, meta) {
17723
+ function getRenamedEntrypoint(entrypoint) {
17724
17724
  const filename = path_1.basename(entrypoint);
17725
17725
  if (filename.startsWith('[')) {
17726
- const suffix = meta.isDev && !entrypoint.endsWith('.go') ? '.go' : '';
17727
- const newEntrypoint = entrypoint.replace('/[', '/now-bracket[') + suffix;
17728
- const file = files[entrypoint];
17729
- delete files[entrypoint];
17730
- files[newEntrypoint] = file;
17726
+ const newEntrypoint = entrypoint.replace('/[', '/now-bracket[');
17731
17727
  build_utils_1.debug(`Renamed entrypoint from ${entrypoint} to ${newEntrypoint}`);
17732
- entrypoint = newEntrypoint;
17728
+ return newEntrypoint;
17733
17729
  }
17734
- return entrypoint;
17730
+ return undefined;
17735
17731
  }
17736
17732
  exports.version = 3;
17737
17733
  async function build({ files, entrypoint, config, workPath, meta = {}, }) {
17738
- if (process.env.GIT_CREDENTIALS && !meta.isDev) {
17739
- build_utils_1.debug('Initialize Git credentials...');
17740
- await initPrivateGit(process.env.GIT_CREDENTIALS);
17741
- }
17742
- if (process.env.GO111MODULE) {
17743
- console.log(`\nManually assigning 'GO111MODULE' is not recommended.
17744
-
17745
- By default:
17746
- - 'GO111MODULE=on' If entrypoint package name is not 'main'
17747
- - 'GO111MODULE=off' If entrypoint package name is 'main'
17748
-
17749
- We highly recommend you leverage Go Modules in your project.
17750
- Learn more: https://github.com/golang/go/wiki/Modules
17751
- `);
17752
- }
17753
- entrypoint = await getRenamedEntrypoint(entrypoint, files, meta);
17754
- const entrypointArr = entrypoint.split(path_1.sep);
17755
- // eslint-disable-next-line prefer-const
17756
- let [goPath, outDir] = await Promise.all([
17757
- build_utils_1.getWriteableDirectory(),
17758
- build_utils_1.getWriteableDirectory(),
17759
- ]);
17760
- const forceMove = Boolean(meta.isDev);
17734
+ const goPath = await build_utils_1.getWriteableDirectory();
17761
17735
  const srcPath = path_1.join(goPath, 'src', 'lambda');
17762
- let downloadPath = meta.isDev || meta.skipDownload ? workPath : srcPath;
17763
- let downloadedFiles = await build_utils_1.download(files, downloadPath, meta);
17764
- build_utils_1.debug(`Parsing AST for "${entrypoint}"`);
17765
- let analyzed;
17736
+ const downloadPath = meta.skipDownload ? workPath : srcPath;
17737
+ await build_utils_1.download(files, downloadPath, meta);
17738
+ // keep track of file system actions we need to undo
17739
+ // the keys "from" and "to" refer to what needs to be done
17740
+ // in order to undo the action, not what the original action was
17741
+ const undoFileActions = [];
17742
+ const undoDirectoryCreation = [];
17766
17743
  try {
17767
- let goModAbsPathDir = '';
17768
- const fileName = 'go.mod';
17769
- if (fileName in downloadedFiles) {
17770
- goModAbsPathDir = path_1.dirname(downloadedFiles[fileName].fsPath);
17771
- build_utils_1.debug(`Found ${fileName} file in "${goModAbsPathDir}"`);
17744
+ if (process.env.GIT_CREDENTIALS) {
17745
+ build_utils_1.debug('Initialize Git credentials...');
17746
+ await initPrivateGit(process.env.GIT_CREDENTIALS);
17772
17747
  }
17773
- else if ('api/go.mod' in downloadedFiles) {
17774
- goModAbsPathDir = path_1.dirname(downloadedFiles['api/go.mod'].fsPath);
17775
- build_utils_1.debug(`Found ${fileName} file in "${goModAbsPathDir}"`);
17748
+ if (process.env.GO111MODULE) {
17749
+ console.log(`\nManually assigning 'GO111MODULE' is not recommended.
17750
+
17751
+ By default:
17752
+ - 'GO111MODULE=on' If entrypoint package name is not 'main'
17753
+ - 'GO111MODULE=off' If entrypoint package name is 'main'
17754
+
17755
+ We highly recommend you leverage Go Modules in your project.
17756
+ Learn more: https://github.com/golang/go/wiki/Modules
17757
+ `);
17776
17758
  }
17777
- analyzed = await go_helpers_1.getAnalyzedEntrypoint(workPath, downloadedFiles[entrypoint].fsPath, goModAbsPathDir);
17778
- }
17779
- catch (err) {
17780
- console.log(`Failed to parse AST for "${entrypoint}"`);
17781
- throw err;
17782
- }
17783
- if (!analyzed) {
17784
- const err = new Error(`Could not find an exported function in "${entrypoint}"
17785
- Learn more: https://vercel.com/docs/runtimes#official-runtimes/go
17786
- `);
17787
- console.log(err.message);
17788
- throw err;
17789
- }
17790
- const parsedAnalyzed = JSON.parse(analyzed);
17791
- if (meta.isDev) {
17792
- // Create cache so Go rebuilds fast with `vercel dev`
17793
- // Old versions of the CLI don't assign this property
17794
- const { devCacheDir = path_1.join(workPath, '.now', 'cache') } = meta;
17795
- goPath = path_1.join(devCacheDir, 'go', path_1.basename(entrypoint, '.go'));
17796
- const destLambda = path_1.join(goPath, 'src', 'lambda');
17797
- await build_utils_1.download(downloadedFiles, destLambda);
17798
- downloadedFiles = await build_utils_1.glob('**', destLambda);
17799
- downloadPath = destLambda;
17800
- }
17801
- // find `go.mod` in downloadedFiles
17802
- const entrypointDirname = path_1.dirname(downloadedFiles[entrypoint].fsPath);
17803
- let isGoModExist = false;
17804
- let goModPath = '';
17805
- let isGoModInRootDir = false;
17806
- for (const file of Object.keys(downloadedFiles)) {
17807
- const { fsPath } = downloadedFiles[file];
17808
- const fileDirname = path_1.dirname(fsPath);
17809
- if (file === 'go.mod') {
17810
- isGoModExist = true;
17811
- isGoModInRootDir = true;
17812
- goModPath = fileDirname;
17759
+ const renamedEntrypoint = getRenamedEntrypoint(entrypoint);
17760
+ if (renamedEntrypoint) {
17761
+ await fs_extra_1.move(path_1.join(workPath, entrypoint), path_1.join(workPath, renamedEntrypoint));
17762
+ undoFileActions.push({
17763
+ to: path_1.join(workPath, entrypoint),
17764
+ from: path_1.join(workPath, renamedEntrypoint),
17765
+ });
17766
+ entrypoint = renamedEntrypoint;
17813
17767
  }
17814
- else if (file.endsWith('go.mod')) {
17815
- if (entrypointDirname === fileDirname) {
17816
- isGoModExist = true;
17817
- goModPath = fileDirname;
17818
- build_utils_1.debug(`Found file dirname equals entrypoint dirname: ${fileDirname}`);
17819
- break;
17768
+ const entrypointAbsolute = path_1.join(workPath, entrypoint);
17769
+ const entrypointArr = entrypoint.split(path_1.sep);
17770
+ build_utils_1.debug(`Parsing AST for "${entrypoint}"`);
17771
+ let analyzed;
17772
+ try {
17773
+ const goModAbsPath = await findGoModPath(workPath);
17774
+ if (goModAbsPath) {
17775
+ build_utils_1.debug(`Found ${goModAbsPath}"`);
17820
17776
  }
17821
- if (!isGoModInRootDir && config.zeroConfig && file === 'api/go.mod') {
17822
- // We didn't find `/go.mod` but we found `/api/go.mod` so move it to the root
17777
+ analyzed = await go_helpers_1.getAnalyzedEntrypoint(workPath, entrypointAbsolute, path_1.dirname(goModAbsPath));
17778
+ }
17779
+ catch (err) {
17780
+ console.log(`Failed to parse AST for "${entrypoint}"`);
17781
+ throw err;
17782
+ }
17783
+ if (!analyzed) {
17784
+ const err = new Error(`Could not find an exported function in "${entrypoint}"
17785
+ Learn more: https://vercel.com/docs/runtimes#official-runtimes/go
17786
+ `);
17787
+ console.log(err.message);
17788
+ throw err;
17789
+ }
17790
+ const parsedAnalyzed = JSON.parse(analyzed);
17791
+ // find `go.mod` in modFiles
17792
+ const entrypointDirname = path_1.dirname(entrypointAbsolute);
17793
+ let isGoModExist = false;
17794
+ let goModPath = '';
17795
+ let isGoModInRootDir = false;
17796
+ const modFileRefs = await build_utils_1.glob('**/*.mod', workPath);
17797
+ const modFiles = Object.keys(modFileRefs);
17798
+ for (const file of modFiles) {
17799
+ const fileDirname = path_1.dirname(file);
17800
+ if (file === 'go.mod') {
17823
17801
  isGoModExist = true;
17824
17802
  isGoModInRootDir = true;
17825
- goModPath = path_1.join(fileDirname, '..');
17826
- const pathParts = fsPath.split(path_1.sep);
17827
- pathParts.pop(); // Remove go.mod
17828
- pathParts.pop(); // Remove api
17829
- pathParts.push('go.mod');
17830
- const newFsPath = pathParts.join(path_1.sep);
17831
- build_utils_1.debug(`Moving api/go.mod to root: ${fsPath} to ${newFsPath}`);
17832
- await fs_extra_1.move(fsPath, newFsPath, { overwrite: forceMove });
17833
- const oldSumPath = path_1.join(path_1.dirname(fsPath), 'go.sum');
17834
- const newSumPath = path_1.join(path_1.dirname(newFsPath), 'go.sum');
17835
- if (await fs_extra_1.pathExists(oldSumPath)) {
17836
- build_utils_1.debug(`Moving api/go.sum to root: ${oldSumPath} to ${newSumPath}`);
17837
- await fs_extra_1.move(oldSumPath, newSumPath, { overwrite: forceMove });
17803
+ goModPath = path_1.join(workPath, fileDirname);
17804
+ }
17805
+ else if (file.endsWith('go.mod')) {
17806
+ if (entrypointDirname === fileDirname) {
17807
+ isGoModExist = true;
17808
+ goModPath = path_1.join(workPath, fileDirname);
17809
+ build_utils_1.debug(`Found file dirname equals entrypoint dirname: ${fileDirname}`);
17810
+ break;
17811
+ }
17812
+ if (!isGoModInRootDir && config.zeroConfig && file === 'api/go.mod') {
17813
+ // We didn't find `/go.mod` but we found `/api/go.mod` so move it to the root
17814
+ isGoModExist = true;
17815
+ isGoModInRootDir = true;
17816
+ goModPath = path_1.join(fileDirname, '..');
17817
+ const pathParts = file.split(path_1.sep);
17818
+ pathParts.pop(); // Remove go.mod
17819
+ pathParts.pop(); // Remove api
17820
+ pathParts.push('go.mod');
17821
+ const newRoot = pathParts.join(path_1.sep);
17822
+ const newFsPath = path_1.join(workPath, newRoot);
17823
+ build_utils_1.debug(`Moving api/go.mod to root: ${file} to ${newFsPath}`);
17824
+ await fs_extra_1.move(file, newFsPath);
17825
+ undoFileActions.push({
17826
+ to: file,
17827
+ from: newFsPath,
17828
+ });
17829
+ const oldSumPath = path_1.join(path_1.dirname(file), 'go.sum');
17830
+ const newSumPath = path_1.join(path_1.dirname(newFsPath), 'go.sum');
17831
+ if (await fs_extra_1.pathExists(oldSumPath)) {
17832
+ build_utils_1.debug(`Moving api/go.sum to root: ${oldSumPath} to ${newSumPath}`);
17833
+ await fs_extra_1.move(oldSumPath, newSumPath);
17834
+ undoFileActions.push({
17835
+ to: oldSumPath,
17836
+ from: newSumPath,
17837
+ });
17838
+ }
17839
+ break;
17838
17840
  }
17839
- break;
17840
17841
  }
17841
17842
  }
17842
- }
17843
- const input = entrypointDirname;
17844
- const includedFiles = {};
17845
- if (config && config.includeFiles) {
17846
- const patterns = Array.isArray(config.includeFiles)
17847
- ? config.includeFiles
17848
- : [config.includeFiles];
17849
- for (const pattern of patterns) {
17850
- const fsFiles = await build_utils_1.glob(pattern, input);
17851
- for (const [assetName, asset] of Object.entries(fsFiles)) {
17852
- includedFiles[assetName] = asset;
17843
+ const input = entrypointDirname;
17844
+ const includedFiles = {};
17845
+ if (config && config.includeFiles) {
17846
+ const patterns = Array.isArray(config.includeFiles)
17847
+ ? config.includeFiles
17848
+ : [config.includeFiles];
17849
+ for (const pattern of patterns) {
17850
+ const fsFiles = await build_utils_1.glob(pattern, input);
17851
+ for (const [assetName, asset] of Object.entries(fsFiles)) {
17852
+ includedFiles[assetName] = asset;
17853
+ }
17853
17854
  }
17854
17855
  }
17855
- }
17856
- const handlerFunctionName = parsedAnalyzed.functionName;
17857
- build_utils_1.debug(`Found exported function "${handlerFunctionName}" in "${entrypoint}"`);
17858
- if (!isGoModExist && 'vendor' in downloadedFiles) {
17859
- throw new Error('`go.mod` is required to use a `vendor` directory.');
17860
- }
17861
- // check if package name other than main
17862
- // using `go.mod` way building the handler
17863
- const packageName = parsedAnalyzed.packageName;
17864
- if (isGoModExist && packageName === 'main') {
17865
- throw new Error('Please change `package main` to `package handler`');
17866
- }
17867
- if (packageName !== 'main') {
17868
- const go = await go_helpers_1.createGo(workPath, goPath, process.platform, process.arch, {
17869
- cwd: entrypointDirname,
17870
- }, true);
17856
+ const handlerFunctionName = parsedAnalyzed.functionName;
17857
+ build_utils_1.debug(`Found exported function "${handlerFunctionName}" in "${entrypoint}"`);
17871
17858
  if (!isGoModExist) {
17859
+ if (await fs_extra_1.pathExists(path_1.join(workPath, 'vendor'))) {
17860
+ throw new Error('`go.mod` is required to use a `vendor` directory.');
17861
+ }
17862
+ }
17863
+ // check if package name other than main
17864
+ // using `go.mod` way building the handler
17865
+ const packageName = parsedAnalyzed.packageName;
17866
+ if (isGoModExist && packageName === 'main') {
17867
+ throw new Error('Please change `package main` to `package handler`');
17868
+ }
17869
+ const outDir = await build_utils_1.getWriteableDirectory();
17870
+ if (packageName !== 'main') {
17871
+ const go = await go_helpers_1.createGo(workPath, goPath, process.platform, process.arch, {
17872
+ cwd: entrypointDirname,
17873
+ }, true);
17874
+ if (!isGoModExist) {
17875
+ try {
17876
+ const defaultGoModContent = `module ${packageName}`;
17877
+ await fs_extra_1.writeFile(path_1.join(entrypointDirname, 'go.mod'), defaultGoModContent);
17878
+ undoFileActions.push({
17879
+ to: undefined,
17880
+ from: path_1.join(entrypointDirname, 'go.mod'),
17881
+ });
17882
+ // remove the `go.sum` file that will be generated as well
17883
+ undoFileActions.push({
17884
+ to: undefined,
17885
+ from: path_1.join(entrypointDirname, 'go.sum'),
17886
+ });
17887
+ }
17888
+ catch (err) {
17889
+ console.log(`Failed to create default go.mod for ${packageName}`);
17890
+ throw err;
17891
+ }
17892
+ }
17893
+ const mainModGoFileName = 'main__mod__.go';
17894
+ const modMainGoContents = await fs_extra_1.readFile(__webpack_require__.ab + "main__mod__.go", 'utf8');
17895
+ let goPackageName = `${packageName}/${packageName}`;
17896
+ const goFuncName = `${packageName}.${handlerFunctionName}`;
17897
+ if (isGoModExist) {
17898
+ const goModContents = await fs_extra_1.readFile(path_1.join(goModPath, 'go.mod'), 'utf8');
17899
+ const usrModName = goModContents.split('\n')[0].split(' ')[1];
17900
+ if (entrypointArr.length > 1 && isGoModInRootDir) {
17901
+ const cleanPackagePath = [...entrypointArr];
17902
+ cleanPackagePath.pop();
17903
+ goPackageName = `${usrModName}/${cleanPackagePath.join('/')}`;
17904
+ }
17905
+ else {
17906
+ goPackageName = `${usrModName}/${packageName}`;
17907
+ }
17908
+ }
17909
+ const mainModGoContents = modMainGoContents
17910
+ .replace('__VC_HANDLER_PACKAGE_NAME', goPackageName)
17911
+ .replace('__VC_HANDLER_FUNC_NAME', goFuncName);
17912
+ if (isGoModExist && isGoModInRootDir) {
17913
+ build_utils_1.debug('[mod-root] Write main file to ' + downloadPath);
17914
+ await fs_extra_1.writeFile(path_1.join(downloadPath, mainModGoFileName), mainModGoContents);
17915
+ undoFileActions.push({
17916
+ to: undefined,
17917
+ from: path_1.join(downloadPath, mainModGoFileName),
17918
+ });
17919
+ }
17920
+ else if (isGoModExist && !isGoModInRootDir) {
17921
+ build_utils_1.debug('[mod-other] Write main file to ' + goModPath);
17922
+ await fs_extra_1.writeFile(path_1.join(goModPath, mainModGoFileName), mainModGoContents);
17923
+ undoFileActions.push({
17924
+ to: undefined,
17925
+ from: path_1.join(goModPath, mainModGoFileName),
17926
+ });
17927
+ }
17928
+ else {
17929
+ build_utils_1.debug('[entrypoint] Write main file to ' + entrypointDirname);
17930
+ await fs_extra_1.writeFile(path_1.join(entrypointDirname, mainModGoFileName), mainModGoContents);
17931
+ undoFileActions.push({
17932
+ to: undefined,
17933
+ from: path_1.join(entrypointDirname, mainModGoFileName),
17934
+ });
17935
+ }
17936
+ // move user go file to folder
17872
17937
  try {
17873
- const defaultGoModContent = `module ${packageName}`;
17874
- await fs_extra_1.writeFile(path_1.join(entrypointDirname, 'go.mod'), defaultGoModContent);
17938
+ // default path
17939
+ let finalDestination = path_1.join(entrypointDirname, packageName, entrypoint);
17940
+ // if `entrypoint` include folder, only use filename
17941
+ if (entrypointArr.length > 1) {
17942
+ finalDestination = path_1.join(entrypointDirname, packageName, entrypointArr[entrypointArr.length - 1]);
17943
+ }
17944
+ if (path_1.dirname(entrypointAbsolute) === goModPath || !isGoModExist) {
17945
+ build_utils_1.debug(`moving entrypoint "${entrypointAbsolute}" to "${finalDestination}"`);
17946
+ await fs_extra_1.move(entrypointAbsolute, finalDestination);
17947
+ undoFileActions.push({
17948
+ to: entrypointAbsolute,
17949
+ from: finalDestination,
17950
+ });
17951
+ undoDirectoryCreation.push(path_1.dirname(finalDestination));
17952
+ }
17875
17953
  }
17876
17954
  catch (err) {
17877
- console.log(`Failed to create default go.mod for ${packageName}`);
17955
+ console.log('Failed to move entry to package folder');
17878
17956
  throw err;
17879
17957
  }
17880
- }
17881
- const mainModGoFileName = 'main__mod__.go';
17882
- const modMainGoContents = await fs_extra_1.readFile(__webpack_require__.ab + "main__mod__.go", 'utf8');
17883
- let goPackageName = `${packageName}/${packageName}`;
17884
- const goFuncName = `${packageName}.${handlerFunctionName}`;
17885
- if (isGoModExist) {
17886
- const goModContents = await fs_extra_1.readFile(path_1.join(goModPath, 'go.mod'), 'utf8');
17887
- const usrModName = goModContents.split('\n')[0].split(' ')[1];
17888
- if (entrypointArr.length > 1 && isGoModInRootDir) {
17889
- const cleanPackagePath = [...entrypointArr];
17890
- cleanPackagePath.pop();
17891
- goPackageName = `${usrModName}/${cleanPackagePath.join('/')}`;
17958
+ let baseGoModPath = '';
17959
+ if (isGoModExist && isGoModInRootDir) {
17960
+ baseGoModPath = downloadPath;
17961
+ }
17962
+ else if (isGoModExist && !isGoModInRootDir) {
17963
+ baseGoModPath = goModPath;
17892
17964
  }
17893
17965
  else {
17894
- goPackageName = `${usrModName}/${packageName}`;
17966
+ baseGoModPath = entrypointDirname;
17895
17967
  }
17896
- }
17897
- const mainModGoContents = modMainGoContents
17898
- .replace('__VC_HANDLER_PACKAGE_NAME', goPackageName)
17899
- .replace('__VC_HANDLER_FUNC_NAME', goFuncName);
17900
- if (isGoModExist && isGoModInRootDir) {
17901
- build_utils_1.debug('[mod-root] Write main file to ' + downloadPath);
17902
- await fs_extra_1.writeFile(path_1.join(downloadPath, mainModGoFileName), mainModGoContents);
17903
- }
17904
- else if (isGoModExist && !isGoModInRootDir) {
17905
- build_utils_1.debug('[mod-other] Write main file to ' + goModPath);
17906
- await fs_extra_1.writeFile(path_1.join(goModPath, mainModGoFileName), mainModGoContents);
17907
- }
17908
- else {
17909
- build_utils_1.debug('[entrypoint] Write main file to ' + entrypointDirname);
17910
- await fs_extra_1.writeFile(path_1.join(entrypointDirname, mainModGoFileName), mainModGoContents);
17911
- }
17912
- // move user go file to folder
17913
- try {
17914
- // default path
17915
- let finalDestination = path_1.join(entrypointDirname, packageName, entrypoint);
17916
- // if `entrypoint` include folder, only use filename
17917
- if (entrypointArr.length > 1) {
17918
- finalDestination = path_1.join(entrypointDirname, packageName, entrypointArr[entrypointArr.length - 1]);
17968
+ build_utils_1.debug('Tidy `go.mod` file...');
17969
+ try {
17970
+ // ensure go.mod up-to-date
17971
+ await go.mod();
17919
17972
  }
17920
- if (path_1.dirname(downloadedFiles[entrypoint].fsPath) === goModPath ||
17921
- !isGoModExist) {
17922
- await fs_extra_1.move(downloadedFiles[entrypoint].fsPath, finalDestination, {
17923
- overwrite: forceMove,
17924
- });
17973
+ catch (err) {
17974
+ console.log('failed to `go mod tidy`');
17975
+ throw err;
17976
+ }
17977
+ build_utils_1.debug('Running `go build`...');
17978
+ const destPath = path_1.join(outDir, handlerFileName);
17979
+ try {
17980
+ const src = [path_1.join(baseGoModPath, mainModGoFileName)];
17981
+ await go.build(src, destPath);
17982
+ }
17983
+ catch (err) {
17984
+ console.log('failed to `go build`');
17985
+ throw err;
17925
17986
  }
17926
- }
17927
- catch (err) {
17928
- console.log('Failed to move entry to package folder');
17929
- throw err;
17930
- }
17931
- let baseGoModPath = '';
17932
- if (isGoModExist && isGoModInRootDir) {
17933
- baseGoModPath = downloadPath;
17934
- }
17935
- else if (isGoModExist && !isGoModInRootDir) {
17936
- baseGoModPath = goModPath;
17937
17987
  }
17938
17988
  else {
17939
- baseGoModPath = entrypointDirname;
17940
- }
17941
- if (meta.isDev) {
17942
- const isGoModBk = await fs_extra_1.pathExists(path_1.join(baseGoModPath, 'go.mod.bk'));
17943
- if (isGoModBk) {
17944
- await fs_extra_1.move(path_1.join(baseGoModPath, 'go.mod.bk'), path_1.join(baseGoModPath, 'go.mod'), { overwrite: forceMove });
17945
- await fs_extra_1.move(path_1.join(baseGoModPath, 'go.sum.bk'), path_1.join(baseGoModPath, 'go.sum'), { overwrite: forceMove });
17989
+ // legacy mode
17990
+ // we need `main.go` in the same dir as the entrypoint,
17991
+ // otherwise `go build` will refuse to build
17992
+ const go = await go_helpers_1.createGo(workPath, goPath, process.platform, process.arch, {
17993
+ cwd: entrypointDirname,
17994
+ }, false);
17995
+ const origianlMainGoContents = await fs_extra_1.readFile(__webpack_require__.ab + "main.go", 'utf8');
17996
+ const mainGoContents = origianlMainGoContents.replace('__VC_HANDLER_FUNC_NAME', handlerFunctionName);
17997
+ // in order to allow the user to have `main.go`,
17998
+ // we need our `main.go` to be called something else
17999
+ const mainGoFileName = 'main__vc__go__.go';
18000
+ // Go doesn't like to build files in different directories,
18001
+ // so now we place `main.go` together with the user code
18002
+ await fs_extra_1.writeFile(path_1.join(entrypointDirname, mainGoFileName), mainGoContents);
18003
+ undoFileActions.push({
18004
+ to: undefined,
18005
+ from: path_1.join(entrypointDirname, mainGoFileName),
18006
+ });
18007
+ // `go get` will look at `*.go` (note we set `cwd`), parse the `import`s
18008
+ // and download any packages that aren't part of the stdlib
18009
+ build_utils_1.debug('Running `go get`...');
18010
+ try {
18011
+ await go.get();
18012
+ }
18013
+ catch (err) {
18014
+ console.log('Failed to `go get`');
18015
+ throw err;
18016
+ }
18017
+ build_utils_1.debug('Running `go build`...');
18018
+ const destPath = path_1.join(outDir, handlerFileName);
18019
+ try {
18020
+ const src = [
18021
+ path_1.join(entrypointDirname, mainGoFileName),
18022
+ entrypointAbsolute,
18023
+ ].map(file => path_1.normalize(file));
18024
+ await go.build(src, destPath);
18025
+ }
18026
+ catch (err) {
18027
+ console.log('failed to `go build`');
18028
+ throw err;
17946
18029
  }
17947
18030
  }
17948
- build_utils_1.debug('Tidy `go.mod` file...');
17949
- try {
17950
- // ensure go.mod up-to-date
17951
- await go.mod();
17952
- }
17953
- catch (err) {
17954
- console.log('failed to `go mod tidy`');
17955
- throw err;
17956
- }
17957
- build_utils_1.debug('Running `go build`...');
17958
- const destPath = path_1.join(outDir, handlerFileName);
17959
- try {
17960
- const src = [path_1.join(baseGoModPath, mainModGoFileName)];
17961
- await go.build(src, destPath);
17962
- }
17963
- catch (err) {
17964
- console.log('failed to `go build`');
17965
- throw err;
17966
- }
17967
- if (meta.isDev) {
17968
- // caching for `vercel dev`
17969
- await fs_extra_1.move(path_1.join(baseGoModPath, 'go.mod'), path_1.join(baseGoModPath, 'go.mod.bk'), { overwrite: forceMove });
17970
- await fs_extra_1.move(path_1.join(baseGoModPath, 'go.sum'), path_1.join(baseGoModPath, 'go.sum.bk'), { overwrite: forceMove });
18031
+ const lambda = await build_utils_1.createLambda({
18032
+ files: { ...(await build_utils_1.glob('**', outDir)), ...includedFiles },
18033
+ handler: handlerFileName,
18034
+ runtime: 'go1.x',
18035
+ environment: {},
18036
+ });
18037
+ const watch = parsedAnalyzed.watch;
18038
+ let watchSub = [];
18039
+ // if `entrypoint` located in subdirectory
18040
+ // we will need to concat it with return watch array
18041
+ if (entrypointArr.length > 1) {
18042
+ entrypointArr.pop();
18043
+ watchSub = parsedAnalyzed.watch.map(file => path_1.join(...entrypointArr, file));
17971
18044
  }
18045
+ return {
18046
+ output: lambda,
18047
+ watch: watch.concat(watchSub),
18048
+ };
17972
18049
  }
17973
- else {
17974
- // legacy mode
17975
- // we need `main.go` in the same dir as the entrypoint,
17976
- // otherwise `go build` will refuse to build
17977
- const go = await go_helpers_1.createGo(workPath, goPath, process.platform, process.arch, {
17978
- cwd: entrypointDirname,
17979
- }, false);
17980
- const origianlMainGoContents = await fs_extra_1.readFile(__webpack_require__.ab + "main.go", 'utf8');
17981
- const mainGoContents = origianlMainGoContents.replace('__VC_HANDLER_FUNC_NAME', handlerFunctionName);
17982
- // in order to allow the user to have `main.go`,
17983
- // we need our `main.go` to be called something else
17984
- const mainGoFileName = 'main__vc__go__.go';
17985
- // Go doesn't like to build files in different directories,
17986
- // so now we place `main.go` together with the user code
17987
- await fs_extra_1.writeFile(path_1.join(entrypointDirname, mainGoFileName), mainGoContents);
17988
- // `go get` will look at `*.go` (note we set `cwd`), parse the `import`s
17989
- // and download any packages that aren't part of the stdlib
17990
- build_utils_1.debug('Running `go get`...');
18050
+ catch (error) {
18051
+ build_utils_1.debug('Go Builder Error: ' + error);
18052
+ throw error;
18053
+ }
18054
+ finally {
17991
18055
  try {
17992
- await go.get();
18056
+ await cleanupFileSystem(undoFileActions, undoDirectoryCreation);
17993
18057
  }
17994
- catch (err) {
17995
- console.log('Failed to `go get`');
17996
- throw err;
18058
+ catch (error) {
18059
+ console.log(`Build cleanup failed: ${error.message}`);
18060
+ build_utils_1.debug('Cleanup Error: ' + error);
17997
18061
  }
17998
- build_utils_1.debug('Running `go build`...');
17999
- const destPath = path_1.join(outDir, handlerFileName);
18000
- try {
18001
- const src = [
18002
- path_1.join(entrypointDirname, mainGoFileName),
18003
- downloadedFiles[entrypoint].fsPath,
18004
- ].map(file => path_1.normalize(file));
18005
- await go.build(src, destPath);
18062
+ }
18063
+ }
18064
+ exports.build = build;
18065
+ async function cleanupFileSystem(undoFileActions, undoDirectoryCreation) {
18066
+ // we have to undo the actions in reverse order in cases
18067
+ // where one file was moved multiple times, which happens
18068
+ // using files that start with brackets
18069
+ for (const action of undoFileActions.reverse()) {
18070
+ if (action.to) {
18071
+ await fs_extra_1.move(action.from, action.to);
18006
18072
  }
18007
- catch (err) {
18008
- console.log('failed to `go build`');
18009
- throw err;
18073
+ else {
18074
+ await fs_extra_1.remove(action.from);
18010
18075
  }
18011
18076
  }
18012
- const lambda = await build_utils_1.createLambda({
18013
- files: { ...(await build_utils_1.glob('**', outDir)), ...includedFiles },
18014
- handler: handlerFileName,
18015
- runtime: 'go1.x',
18016
- environment: {},
18077
+ const undoDirectoryPromises = undoDirectoryCreation.map(async (directory) => {
18078
+ const contents = await fs_extra_1.readdir(directory);
18079
+ // only delete an empty directory
18080
+ // if it has contents, either something went wrong during cleanup or this
18081
+ // directory contains project source code that should not be deleted
18082
+ if (!contents.length) {
18083
+ return fs_extra_1.rmdir(directory);
18084
+ }
18085
+ return undefined;
18017
18086
  });
18018
- const watch = parsedAnalyzed.watch;
18019
- let watchSub = [];
18020
- // if `entrypoint` located in subdirectory
18021
- // we will need to concat it with return watch array
18022
- if (entrypointArr.length > 1) {
18023
- entrypointArr.pop();
18024
- watchSub = parsedAnalyzed.watch.map(file => path_1.join(...entrypointArr, file));
18087
+ await Promise.all(undoDirectoryPromises);
18088
+ }
18089
+ async function findGoModPath(workPath) {
18090
+ let checkPath = path_1.join(workPath, 'go.mod');
18091
+ if (await fs_extra_1.pathExists(checkPath)) {
18092
+ return checkPath;
18025
18093
  }
18026
- return {
18027
- output: lambda,
18028
- watch: watch.concat(watchSub),
18029
- };
18094
+ checkPath = path_1.join(workPath, 'api/go.mod');
18095
+ if (await fs_extra_1.pathExists(checkPath)) {
18096
+ return checkPath;
18097
+ }
18098
+ return '';
18030
18099
  }
18031
- exports.build = build;
18032
18100
  function isPortInfo(v) {
18033
18101
  return v && typeof v.port === 'number';
18034
18102
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vercel/go",
3
- "version": "2.0.11",
3
+ "version": "2.0.14",
4
4
  "license": "MIT",
5
5
  "main": "./dist/index",
6
6
  "homepage": "https://vercel.com/docs/runtimes#official-runtimes/go",
@@ -11,9 +11,8 @@
11
11
  },
12
12
  "scripts": {
13
13
  "build": "node build",
14
- "test": "yarn jest --env node --verbose --runInBand --bail",
15
- "test-integration-once": "yarn test",
16
- "prepublishOnly": "node build"
14
+ "test": "jest --env node --verbose --runInBand --bail",
15
+ "test-integration-once": "yarn test"
17
16
  },
18
17
  "files": [
19
18
  "dist"
@@ -25,7 +24,7 @@
25
24
  "@types/fs-extra": "^5.0.5",
26
25
  "@types/node-fetch": "^2.3.0",
27
26
  "@types/tar": "^4.0.0",
28
- "@vercel/build-utils": "5.0.7",
27
+ "@vercel/build-utils": "5.1.1",
29
28
  "@vercel/ncc": "0.24.0",
30
29
  "async-retry": "1.3.1",
31
30
  "execa": "^1.0.0",
@@ -35,5 +34,5 @@
35
34
  "tar": "4.4.6",
36
35
  "typescript": "4.3.4"
37
36
  },
38
- "gitHead": "e8c7db59cf2746422f1f7e14cc6b7f901c243d50"
37
+ "gitHead": "5eb8b16cbdf6215618b4b8125673941757fa1a8e"
39
38
  }