google-apps-scriptloggingexecution

Google Apps - Script executes another script without calling a function of it


Script01.gs

function list_folders_with_no_files_and_subfolders() {
  var folders = DriveApp.getFolders();
  var folderNames = [];
  
  while (folders.hasNext()) {
    var subFolder = folders.next();
    var files = subFolder.getFiles();
    var subFolders = subFolder.getFolders();

    if (files.hasNext()  || subFolders.hasNext()  ) { 
      continue;

    }

      var name = subFolder.getName();
      folderNames.push(name);
    
  }

  
  Logger.log("Log Script 01:");
  folderNames.forEach(function(name) {
    Logger.log(name);
  });
}

Script02.gs

function listAllFolders() {
  var rootFolder = DriveApp.getFolderById('YOUR_FOLDER_ID');
  var folderNamesToCheck = [];
  
  if (rootFolder) {
    var folders = rootFolder.getFolders();
    while (folders.hasNext()) {
      var subFolder = folders.next();
      folderNamesToCheck.push(subFolder);
      listSubFolders(subFolder, folderNamesToCheck);
    }
  }
  
  return folderNamesToCheck;
}



function listSubFolders(folder, folderNamesToCheck) {
  var subFolders = folder.getFolders();
  while (subFolders.hasNext()) {
    var subFolder = subFolders.next();
    folderNamesToCheck.push(subFolder);
    listSubFolders(subFolder, folderNamesToCheck);
  }
}




function listEmptyFolders() {
  var emptyFolders = [];
  var folderNamesToCheck = listAllFolders();
  
  folderNamesToCheck.forEach(function(folder) {
    var subFolders = folder.getFolders();
    var files = folder.getFiles();
    
    if (!files.hasNext() && !subFolders.hasNext()) { 
      emptyFolders.push(folder.getName());
    }
  });
  
  return emptyFolders;
}





var emptyFolders = listEmptyFolders();
Logger.log("Log Script 02:");
Logger.log(emptyFolders);

When I execute Script01, I notice that the execution log displays the message "Log Script 02:" before showing the log messages from Script01.

However, when I execute Script02, I only see the message "Log Script 02:", which seems correct.

So what in Script01 triggers a function in Script02? All functions have unique names, and when I'm in Script01, the only function I can select is list_folders_with_no_files_and_subfolders, which is correct. But it still triggers something in Script02.

Thank you!

I expect to see only the execution log of Script01 (list_folders_with_no_files_and_subfolders) and nothing nothing from Script02.


Solution

  • When you execute Script01, execution log displays the message "Log Script 02:" because

    var emptyFolders = listEmptyFolders();
    Logger.log("Log Script 02:");
    Logger.log(emptyFolders);
    

    are in global visibility, and first IDE run the function listEmptyFolders() and then it's your function list_folders_with_no_files_and_subfolders()

    remove this

    var emptyFolders = listEmptyFolders();
    Logger.log("Log Script 02:");
    Logger.log(emptyFolders);
    

    from global visibility