Получение списка функций в вашем проекте GAS - PullRequest
1 голос
/ 11 апреля 2019

Я хочу посмотреть, есть ли способ получить список всех функций, которые у меня есть в проекте Google Apps Script.Я видел несколько потоков при получении списка всех ваших проектов Google Apps Script, но пока нет ни одного для перечисления всех функций в каждом проекте.Кто-нибудь знает возможно ли это?Я просмотрел справочный обзор сценариев Служб Google, но не смог найти ничего, что могло бы мне понравиться (я, конечно, мог его пропустить).Если у кого-то есть какие-либо предложения, пожалуйста, дайте мне знать!.

Лучший пример, который я могу привести:

У меня есть файл электронной таблицы Google.В приложении Google Spreadsheet находится проект GAS (доступ к которому осуществляется через меню Google Sheet «Инструменты -> Редактор скриптов»), в котором есть несколько различных функций, используемых для получения значений из листа, выполнения некоторых вычислений и публикации результатов на другом листе..

Что я пытаюсь выполнить: Запустить какую-то функцию, которая может предоставить мне список всех функций, которые у меня есть в проекте GAS (предпочтительно в виде строковых значений).Примером может быть:

["runMyCalculations","myOnEdit","sortClosedFiles","formatSheets"]

Все эти функции могут быть запущены, только если я открою Редактор скриптов и выберу его в раскрывающемся меню и нажму кнопку «Выполнить».

Я хочу иметь возможность создавать динамический список всех функций, которые у меня есть, чтобы я мог передать их в запускаемую функцию «при открытии», которая создает пользовательское меню на листе, перечисляя все функцииЯ имею.Я хочу, чтобы я мог просто внести изменения в свой лист, перейти в раскрывающееся меню и запустить нужную мне функцию, а не открывать редактор скриптов.

1 Ответ

0 голосов
/ 11 апреля 2019

Вы можете использовать API скриптов приложений, чтобы получить весь контент из файла скриптов приложений. Следующий код имеет возможность передать имя файла для получения. Вы должны предоставить идентификатор файла скрипта приложения. Передача имени файла gs необязательна. Предусмотрено 3 функции. Функция, которая выполняет всю работу, функция для вызова этой функции с параметрами для тестирования и функция регистрации. Библиотека OAuth не нужна, поскольку токен получен из службы ScriptApp.

ПРИМЕЧАНИЕ. Чтобы этот код работал, вам нужно включить API сценариев приложений и утвердить разрешение на диске. Обязательно проверьте возврат от звонка UrlFetchApp.fetch() при первом запуске этого кода для сообщения об ошибке. Он может содержать ссылку, которую необходимо использовать для включения API скриптов приложений.

function getFuncNames(po) {
  var allFiles,dataContentAsString,downloadUrl,fileContents,fileData,i,options,
      theAccessTkn,thisFileName;
  var ndxOfFunction=0,counter=0, ndxOfEnd=0, functionName="", allFncNames=[],
      hasSpaces = 0;
  var innerObj, thisFile, fileType = "", thisGS_Content,howManyFiles, allGsContent="";

  /*
    Get all script function names.  If no gs file name is provided, the code
    gets all the function names.
  */

  /*
    po.fileID - required - The Apps Script file ID
    po.gsFileName - optional - the gs code file name to get - gets just one 
       file instead of all files
  */

  //ll('po',po);

  if (!po.fileID) {
    return false;
  }

  theAccessTkn = ScriptApp.getOAuthToken();//Get an access token for OAuth

  downloadUrl = "https://script.google.com/feeds/download/export?id=" +
      po.fileID + "&format=json";//create url

  options = {
    "kind": "drive#file",
    "id": po.fileID,
    "downloadUrl": downloadUrl,
    "headers": {
       'Authorization': 'Bearer ' +  theAccessTkn,
     },
    "contentType": "application/vnd.google-apps.script+json",
    "method" : "GET"
  };

  fileData = UrlFetchApp.fetch(downloadUrl, options);//Get all the content from the Apps Script file
  //ll('fileData',fileData)

  dataContentAsString = fileData.getContentText();

  fileContents = JSON.parse(dataContentAsString);//Parse string into object

  allFiles = fileContents.files;//All the files in the Apps Script project

  howManyFiles = allFiles.length;

  for (i=0;i<howManyFiles;i++) {
    thisFile = allFiles[i];//Get one inner element that represents one file
    if (!thisFile) {continue;}

    fileType = thisFile.type;
    if (fileType !== "server_js") {continue;}//This is not a gs file - its HTML or json

    thisFileName = thisFile.name;
    //ll('typeof thisFileName',typeof thisFileName)
    //ll('thisFileName',thisFileName)
    //ll('equal',po.gsFileName !== thisFile.name)

    if (po.gsFileName) {//Is there a setting for the file name to restrict the search to
      if (po.gsFileName !== thisFile.name) {//The name to search for is not this file name
        continue;
      }
    }

    thisGS_Content = thisFile.source;//source is the key name for the file content
    allGsContent = allGsContent + thisGS_Content;
  }

  //ll('allGsContent',allGsContent)

  while (ndxOfFunction !== -1 || counter < 1000) {
    ndxOfFunction = allGsContent.indexOf("function ");

    //ll('ndxOfFunction',ndxOfFunction)
    if (ndxOfFunction === -1) {break};

    allGsContent = allGsContent.slice(ndxOfFunction+9);//Remove everything in front of 'function' first

    ndxOfEnd = allGsContent.indexOf("(");
    functionName = allGsContent.slice(0,ndxOfEnd);
    allGsContent = allGsContent.slice(ndxOfEnd+2);//Remove the     
    hasSpaces = functionName.indexOf(" ");

    if (hasSpaces !== -1) {continue;}

    if (functionName.length < 150) {
      allFncNames.push(functionName);
    }//Any string over 150 long is probably not a function name

    counter ++;
  };

  //ll('allFncNames',allFncNames)
  return allFncNames;
};

function runOtherFnk() {
  getFuncNames({fileID:"Your File ID here",gsFileName:"Code"});
}

function ll(a,b) {
  //Logger.log(typeof a)

  if (typeof b === 'object') {
    b = JSON.stringify(b);
  }

  Logger.log(a + ":" + b)
}

Следующий код извлекает имена файлов из объекта this:

function getAllFnks() {
  var allFnks,fnkStr,k;

  allFnks = [];

  for (k in this) {
    //Logger.log(k)
    //Logger.log(typeof k)
    //Logger.log(this[k])
    //Logger.log(typeof this[k])

    fnkStr = this[k];

    if (fnkStr) {
      fnkStr = fnkStr.toString();
      //Logger.log(typeof fnkStr)
    } else {
      continue;
    }

    //Logger.log(fnkStr.toString().indexOf('function'))
    if (fnkStr.indexOf('function') === 1) {
      allFnks.push(k);
    }
  }

  Logger.log(allFnks)
  Logger.log('Number of functions: ' + allFnks.length)
}
...