@vercel/go 2.0.12 → 2.0.15

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 +330 -236
  2. package/package.json +5 -6
package/dist/index.js CHANGED
@@ -17720,289 +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) {
17723
+ function getRenamedEntrypoint(entrypoint) {
17724
17724
  const filename = path_1.basename(entrypoint);
17725
17725
  if (filename.startsWith('[')) {
17726
17726
  const newEntrypoint = entrypoint.replace('/[', '/now-bracket[');
17727
- const file = files[entrypoint];
17728
- delete files[entrypoint];
17729
- files[newEntrypoint] = file;
17730
17727
  build_utils_1.debug(`Renamed entrypoint from ${entrypoint} to ${newEntrypoint}`);
17731
- entrypoint = newEntrypoint;
17728
+ return newEntrypoint;
17732
17729
  }
17733
- return entrypoint;
17730
+ return undefined;
17734
17731
  }
17735
17732
  exports.version = 3;
17736
17733
  async function build({ files, entrypoint, config, workPath, meta = {}, }) {
17737
- if (process.env.GIT_CREDENTIALS) {
17738
- build_utils_1.debug('Initialize Git credentials...');
17739
- await initPrivateGit(process.env.GIT_CREDENTIALS);
17740
- }
17741
- if (process.env.GO111MODULE) {
17742
- console.log(`\nManually assigning 'GO111MODULE' is not recommended.
17743
-
17744
- By default:
17745
- - 'GO111MODULE=on' If entrypoint package name is not 'main'
17746
- - 'GO111MODULE=off' If entrypoint package name is 'main'
17747
-
17748
- We highly recommend you leverage Go Modules in your project.
17749
- Learn more: https://github.com/golang/go/wiki/Modules
17750
- `);
17751
- }
17752
- entrypoint = await getRenamedEntrypoint(entrypoint, files);
17753
- const entrypointArr = entrypoint.split(path_1.sep);
17754
- // eslint-disable-next-line prefer-const
17755
- let [goPath, outDir] = await Promise.all([
17756
- build_utils_1.getWriteableDirectory(),
17757
- build_utils_1.getWriteableDirectory(),
17758
- ]);
17734
+ const goPath = await build_utils_1.getWriteableDirectory();
17759
17735
  const srcPath = path_1.join(goPath, 'src', 'lambda');
17760
17736
  const downloadPath = meta.skipDownload ? workPath : srcPath;
17761
- const downloadedFiles = await build_utils_1.download(files, downloadPath, meta);
17762
- build_utils_1.debug(`Parsing AST for "${entrypoint}"`);
17763
- let analyzed;
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 = [];
17764
17743
  try {
17765
- let goModAbsPathDir = '';
17766
- const fileName = 'go.mod';
17767
- if (fileName in downloadedFiles) {
17768
- goModAbsPathDir = path_1.dirname(downloadedFiles[fileName].fsPath);
17769
- 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);
17770
17747
  }
17771
- else if ('api/go.mod' in downloadedFiles) {
17772
- goModAbsPathDir = path_1.dirname(downloadedFiles['api/go.mod'].fsPath);
17773
- 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
+ `);
17774
17758
  }
17775
- analyzed = await go_helpers_1.getAnalyzedEntrypoint(workPath, downloadedFiles[entrypoint].fsPath, goModAbsPathDir);
17776
- }
17777
- catch (err) {
17778
- console.log(`Failed to parse AST for "${entrypoint}"`);
17779
- throw err;
17780
- }
17781
- if (!analyzed) {
17782
- const err = new Error(`Could not find an exported function in "${entrypoint}"
17783
- Learn more: https://vercel.com/docs/runtimes#official-runtimes/go
17784
- `);
17785
- console.log(err.message);
17786
- throw err;
17787
- }
17788
- const parsedAnalyzed = JSON.parse(analyzed);
17789
- // find `go.mod` in downloadedFiles
17790
- const entrypointDirname = path_1.dirname(downloadedFiles[entrypoint].fsPath);
17791
- let isGoModExist = false;
17792
- let goModPath = '';
17793
- let isGoModInRootDir = false;
17794
- for (const file of Object.keys(downloadedFiles)) {
17795
- const { fsPath } = downloadedFiles[file];
17796
- const fileDirname = path_1.dirname(fsPath);
17797
- if (file === 'go.mod') {
17798
- isGoModExist = true;
17799
- isGoModInRootDir = true;
17800
- 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;
17801
17767
  }
17802
- else if (file.endsWith('go.mod')) {
17803
- if (entrypointDirname === fileDirname) {
17804
- isGoModExist = true;
17805
- goModPath = fileDirname;
17806
- build_utils_1.debug(`Found file dirname equals entrypoint dirname: ${fileDirname}`);
17807
- 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}"`);
17808
17776
  }
17809
- if (!isGoModInRootDir && config.zeroConfig && file === 'api/go.mod') {
17810
- // 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') {
17811
17801
  isGoModExist = true;
17812
17802
  isGoModInRootDir = true;
17813
- goModPath = path_1.join(fileDirname, '..');
17814
- const pathParts = fsPath.split(path_1.sep);
17815
- pathParts.pop(); // Remove go.mod
17816
- pathParts.pop(); // Remove api
17817
- pathParts.push('go.mod');
17818
- const newFsPath = pathParts.join(path_1.sep);
17819
- build_utils_1.debug(`Moving api/go.mod to root: ${fsPath} to ${newFsPath}`);
17820
- await fs_extra_1.move(fsPath, newFsPath);
17821
- const oldSumPath = path_1.join(path_1.dirname(fsPath), 'go.sum');
17822
- const newSumPath = path_1.join(path_1.dirname(newFsPath), 'go.sum');
17823
- if (await fs_extra_1.pathExists(oldSumPath)) {
17824
- build_utils_1.debug(`Moving api/go.sum to root: ${oldSumPath} to ${newSumPath}`);
17825
- await fs_extra_1.move(oldSumPath, newSumPath);
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;
17826
17840
  }
17827
- break;
17828
17841
  }
17829
17842
  }
17830
- }
17831
- const input = entrypointDirname;
17832
- const includedFiles = {};
17833
- if (config && config.includeFiles) {
17834
- const patterns = Array.isArray(config.includeFiles)
17835
- ? config.includeFiles
17836
- : [config.includeFiles];
17837
- for (const pattern of patterns) {
17838
- const fsFiles = await build_utils_1.glob(pattern, input);
17839
- for (const [assetName, asset] of Object.entries(fsFiles)) {
17840
- 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
+ }
17841
17854
  }
17842
17855
  }
17843
- }
17844
- const handlerFunctionName = parsedAnalyzed.functionName;
17845
- build_utils_1.debug(`Found exported function "${handlerFunctionName}" in "${entrypoint}"`);
17846
- if (!isGoModExist && 'vendor' in downloadedFiles) {
17847
- throw new Error('`go.mod` is required to use a `vendor` directory.');
17848
- }
17849
- // check if package name other than main
17850
- // using `go.mod` way building the handler
17851
- const packageName = parsedAnalyzed.packageName;
17852
- if (isGoModExist && packageName === 'main') {
17853
- throw new Error('Please change `package main` to `package handler`');
17854
- }
17855
- if (packageName !== 'main') {
17856
- const go = await go_helpers_1.createGo(workPath, goPath, process.platform, process.arch, {
17857
- cwd: entrypointDirname,
17858
- }, true);
17856
+ const handlerFunctionName = parsedAnalyzed.functionName;
17857
+ build_utils_1.debug(`Found exported function "${handlerFunctionName}" in "${entrypoint}"`);
17859
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
17860
17937
  try {
17861
- const defaultGoModContent = `module ${packageName}`;
17862
- 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
+ }
17863
17953
  }
17864
17954
  catch (err) {
17865
- console.log(`Failed to create default go.mod for ${packageName}`);
17955
+ console.log('Failed to move entry to package folder');
17866
17956
  throw err;
17867
17957
  }
17868
- }
17869
- const mainModGoFileName = 'main__mod__.go';
17870
- const modMainGoContents = await fs_extra_1.readFile(__webpack_require__.ab + "main__mod__.go", 'utf8');
17871
- let goPackageName = `${packageName}/${packageName}`;
17872
- const goFuncName = `${packageName}.${handlerFunctionName}`;
17873
- if (isGoModExist) {
17874
- const goModContents = await fs_extra_1.readFile(path_1.join(goModPath, 'go.mod'), 'utf8');
17875
- const usrModName = goModContents.split('\n')[0].split(' ')[1];
17876
- if (entrypointArr.length > 1 && isGoModInRootDir) {
17877
- const cleanPackagePath = [...entrypointArr];
17878
- cleanPackagePath.pop();
17879
- goPackageName = `${usrModName}/${cleanPackagePath.join('/')}`;
17958
+ let baseGoModPath = '';
17959
+ if (isGoModExist && isGoModInRootDir) {
17960
+ baseGoModPath = downloadPath;
17961
+ }
17962
+ else if (isGoModExist && !isGoModInRootDir) {
17963
+ baseGoModPath = goModPath;
17880
17964
  }
17881
17965
  else {
17882
- goPackageName = `${usrModName}/${packageName}`;
17966
+ baseGoModPath = entrypointDirname;
17883
17967
  }
17884
- }
17885
- const mainModGoContents = modMainGoContents
17886
- .replace('__VC_HANDLER_PACKAGE_NAME', goPackageName)
17887
- .replace('__VC_HANDLER_FUNC_NAME', goFuncName);
17888
- if (isGoModExist && isGoModInRootDir) {
17889
- build_utils_1.debug('[mod-root] Write main file to ' + downloadPath);
17890
- await fs_extra_1.writeFile(path_1.join(downloadPath, mainModGoFileName), mainModGoContents);
17891
- }
17892
- else if (isGoModExist && !isGoModInRootDir) {
17893
- build_utils_1.debug('[mod-other] Write main file to ' + goModPath);
17894
- await fs_extra_1.writeFile(path_1.join(goModPath, mainModGoFileName), mainModGoContents);
17895
- }
17896
- else {
17897
- build_utils_1.debug('[entrypoint] Write main file to ' + entrypointDirname);
17898
- await fs_extra_1.writeFile(path_1.join(entrypointDirname, mainModGoFileName), mainModGoContents);
17899
- }
17900
- // move user go file to folder
17901
- try {
17902
- // default path
17903
- let finalDestination = path_1.join(entrypointDirname, packageName, entrypoint);
17904
- // if `entrypoint` include folder, only use filename
17905
- if (entrypointArr.length > 1) {
17906
- 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();
17907
17972
  }
17908
- if (path_1.dirname(downloadedFiles[entrypoint].fsPath) === goModPath ||
17909
- !isGoModExist) {
17910
- await fs_extra_1.move(downloadedFiles[entrypoint].fsPath, finalDestination);
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;
17911
17986
  }
17912
- }
17913
- catch (err) {
17914
- console.log('Failed to move entry to package folder');
17915
- throw err;
17916
- }
17917
- let baseGoModPath = '';
17918
- if (isGoModExist && isGoModInRootDir) {
17919
- baseGoModPath = downloadPath;
17920
- }
17921
- else if (isGoModExist && !isGoModInRootDir) {
17922
- baseGoModPath = goModPath;
17923
17987
  }
17924
17988
  else {
17925
- baseGoModPath = entrypointDirname;
17926
- }
17927
- build_utils_1.debug('Tidy `go.mod` file...');
17928
- try {
17929
- // ensure go.mod up-to-date
17930
- await go.mod();
17931
- }
17932
- catch (err) {
17933
- console.log('failed to `go mod tidy`');
17934
- throw err;
17935
- }
17936
- build_utils_1.debug('Running `go build`...');
17937
- const destPath = path_1.join(outDir, handlerFileName);
17938
- try {
17939
- const src = [path_1.join(baseGoModPath, mainModGoFileName)];
17940
- await go.build(src, destPath);
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;
18029
+ }
17941
18030
  }
17942
- catch (err) {
17943
- console.log('failed to `go build`');
17944
- throw err;
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));
17945
18044
  }
18045
+ return {
18046
+ output: lambda,
18047
+ watch: watch.concat(watchSub),
18048
+ };
17946
18049
  }
17947
- else {
17948
- // legacy mode
17949
- // we need `main.go` in the same dir as the entrypoint,
17950
- // otherwise `go build` will refuse to build
17951
- const go = await go_helpers_1.createGo(workPath, goPath, process.platform, process.arch, {
17952
- cwd: entrypointDirname,
17953
- }, false);
17954
- const origianlMainGoContents = await fs_extra_1.readFile(__webpack_require__.ab + "main.go", 'utf8');
17955
- const mainGoContents = origianlMainGoContents.replace('__VC_HANDLER_FUNC_NAME', handlerFunctionName);
17956
- // in order to allow the user to have `main.go`,
17957
- // we need our `main.go` to be called something else
17958
- const mainGoFileName = 'main__vc__go__.go';
17959
- // Go doesn't like to build files in different directories,
17960
- // so now we place `main.go` together with the user code
17961
- await fs_extra_1.writeFile(path_1.join(entrypointDirname, mainGoFileName), mainGoContents);
17962
- // `go get` will look at `*.go` (note we set `cwd`), parse the `import`s
17963
- // and download any packages that aren't part of the stdlib
17964
- 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 {
17965
18055
  try {
17966
- await go.get();
18056
+ await cleanupFileSystem(undoFileActions, undoDirectoryCreation);
17967
18057
  }
17968
- catch (err) {
17969
- console.log('Failed to `go get`');
17970
- throw err;
18058
+ catch (error) {
18059
+ console.log(`Build cleanup failed: ${error.message}`);
18060
+ build_utils_1.debug('Cleanup Error: ' + error);
17971
18061
  }
17972
- build_utils_1.debug('Running `go build`...');
17973
- const destPath = path_1.join(outDir, handlerFileName);
17974
- try {
17975
- const src = [
17976
- path_1.join(entrypointDirname, mainGoFileName),
17977
- downloadedFiles[entrypoint].fsPath,
17978
- ].map(file => path_1.normalize(file));
17979
- 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);
17980
18072
  }
17981
- catch (err) {
17982
- console.log('failed to `go build`');
17983
- throw err;
18073
+ else {
18074
+ await fs_extra_1.remove(action.from);
17984
18075
  }
17985
18076
  }
17986
- const lambda = await build_utils_1.createLambda({
17987
- files: { ...(await build_utils_1.glob('**', outDir)), ...includedFiles },
17988
- handler: handlerFileName,
17989
- runtime: 'go1.x',
17990
- 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;
17991
18086
  });
17992
- const watch = parsedAnalyzed.watch;
17993
- let watchSub = [];
17994
- // if `entrypoint` located in subdirectory
17995
- // we will need to concat it with return watch array
17996
- if (entrypointArr.length > 1) {
17997
- entrypointArr.pop();
17998
- 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;
17999
18093
  }
18000
- return {
18001
- output: lambda,
18002
- watch: watch.concat(watchSub),
18003
- };
18094
+ checkPath = path_1.join(workPath, 'api/go.mod');
18095
+ if (await fs_extra_1.pathExists(checkPath)) {
18096
+ return checkPath;
18097
+ }
18098
+ return '';
18004
18099
  }
18005
- exports.build = build;
18006
18100
  function isPortInfo(v) {
18007
18101
  return v && typeof v.port === 'number';
18008
18102
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vercel/go",
3
- "version": "2.0.12",
3
+ "version": "2.0.15",
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.8",
27
+ "@vercel/build-utils": "5.2.0",
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": "543ffdfe5ccfb59c9c455fc50df3bb8ed1eaf567"
37
+ "gitHead": "32afd67d29d46f67027091ab9695d8ff330355b5"
39
38
  }