프로젝트 가져오기 및 내보내기

Apps Script 프로젝트는 Google Drive에 있으므로 개발자는 Google Drive API(Apps Script의 Drive 서비스와 혼동하지 마세요)를 사용하여 Apps Script 소스 코드를 가져오고 내보낼 수 있습니다.

예를 들어 개발자는 로컬 머신에서 좋아하는 코드 편집기로 새 Apps Script 코드를 작성하고 Git과 같은 버전 제어 시스템을 사용하여 다른 개발자와 공동작업할 수 있습니다. 버전이 완성되면 REST API를 사용하여 파일을 Google Drive에 업로드 (가져오기)할 수 있으며, 여기에서 다른 Apps Script 프로젝트와 마찬가지로 사용할 수 있습니다.

로컬 버전에서 코드를 변경하고 Google Drive API를 사용하여 Apps Script 프로젝트에 동기화할 수 있습니다. 기존 프로젝트는 Google Drive에서 로컬 머신으로 다운로드(내보내기)할 수 있습니다.

기능 및 제한사항

Google Drive API를 사용하여 프로젝트를 가져오거나 내보내려면 다음 사항에 유의하세요.

  1. 서버 측 스크립트 파일은 '.gs'로 끝나야 합니다. .js 파일을 사용하여 로컬에서 개발할 수 있지만 Google Drive로 가져오기 전에 파일 이름을 변경하여 .gs 확장자를 포함해야 합니다.
  2. 클라이언트 측 스크립트 파일은 '.html'로 끝나야 합니다. 여기에는 클라이언트 측 .html, .js 또는 .css 파일이 포함됩니다. 다른 확장 프로그램을 사용하여 로컬에서 개발할 수도 있지만 Google Drive로 가져오기 전에 .html 확장자가 있어야 합니다.
  3. 프로젝트 파일을 Google Drive로 가져오면 해당 파일의 기존 데이터가 모두 덮어쓰기됩니다. 일부 텍스트를 추가하거나 삽입할 수 없습니다. 전체 파일을 업데이트해야 합니다.
  4. 서버 측 스크립트 파일에는 유효한 JavaScript가 포함되어야 합니다. 서버 .js 파일에 오류가 있으면 Google Drive API 업데이트 호출이 5xx 오류로 실패합니다. 가져오기 전에 코드를 린트하면 이를 방지할 수 있습니다.
  5. 빈 파일은 가져올 수 없습니다. 빈 파일을 업로드하려고 하면 Google Drive API 업데이트 호출이 5xx 오류로 실패합니다.
  6. 독립형 스크립트만 가져오거나 내보낼 수 있습니다. 컨테이너에 연결된 스크립트는 Google Drive API를 통해 액세스할 수 없습니다.
  7. 소스 코드만 가져오거나 내보낼 수 있습니다. 프로젝트 속성 또는 로그와 같은 리소스도 Google Drive API를 통해 노출되지 않습니다. 스크립트 버전 관리, 스크립트 게시 또는 실행과 같은 작업은 Google Drive API를 통해 할 수 없습니다.
  8. 단일 서버 Code.gs 파일로 제한되지 않습니다. 개발을 쉽게 하기 위해 여러 파일에 서버 코드를 분산할 수 있습니다. 모든 서버 파일은 동일한 글로벌 네임스페이스에 로드되므로 안전한 캡슐화를 제공하려면 JavaScript 클래스를 사용하세요.

Drive API

Google Drive API를 사용하면 개발자가 프로그래매틱 방식으로 Google Drive의 파일에 액세스할 수 있습니다. 이 API는 GET를 사용하여 파일을 다운로드하고 PUT/POST를 사용하여 파일을 업로드합니다. 자세한 문서와 빠른 시작은 Google Drive API 개요 페이지를 참고하세요.

이 가이드에서는 다음 호출을 사용하여 파일 리소스로 파일을 나열하고 이동하는 방법을 중점적으로 설명합니다.

승인

Google Drive API에 대한 모든 요청은 인증된 사용자가 OAuth 2.0 프로토콜을 통해 승인해야 합니다. 자세한 내용은 Google Drive API 승인 문서를 참고하세요.

애플리케이션에 필요한 다른 범위(예: https://www.googleapis.com/auth/drive) 외에도 Google Apps Script 프로젝트를 가져오거나 내보내려고 시도하는 모든 애플리케이션은 다음과 같은 특수 범위를 요청해야 합니다.

https://www.googleapis.com/auth/drive.scripts

기존 프로젝트 나열

Drive의 모든 Apps Script 프로젝트를 나열하려면 파일 리소스를 사용하여 MIME 유형이 application/vnd.google-apps.script인 파일을 쿼리합니다. 소유한 파일만 포함되도록 응답을 필터링하려면 검색 매개변수 'me' in owners를 포함합니다.

다음은 JSON 응답을 통해 반환된 Apps Script 프로젝트 배열을 보여주는 샘플 요청 및 응답입니다.

GET https://www.googleapis.com/drive/v2/files?q=mimeType%3D'application%2Fvnd.google-apps.script'+and+'me'+in+owners
Authorization:  Bearer ya29.fakebearerstring
{
 "kind": "drive#fileList",
 "etag": "\"kjsas92/f3zGUXczKMxEB_9ZTMRFOF3d1ZU\"",
 "selfLink": "https://www.googleapis.com/drive/v2/files?q=mimeType%3D'application/vnd.google-apps.script'+and+'me'+in+owners",
 "items": [
  {
   "kind": "drive#file",
   "id": "1vi0uwcMdHsRv1YFtgq7XdiTGSdqgjIYpdQNC0A_Udn79LOhH0vYL132D",
   "etag": "\"kjsas92/MTM3MDk3ODY5ODQyNg\"",
   "selfLink": "https://www.googleapis.com/drive/v2/files/1vi0uwcMdHsRv1YFtgq7XdiTGSdqgjIYpdQNC0A_Udn79LOhH0vYL132D",
   "alternateLink": "https://script.google.com/a/google.com/d/1vi0uwcMdHsRv1YFtgq7XdiTGSdqgjIYpdQNC0A_Udn79LOhH0vYL132D/edit?usp=drivesdk",
   "iconLink": "https://ssl.gstatic.com/docs/doclist/images/icon_11_script_list.png",
   "title": "Mail merge",
   "mimeType": "application/vnd.google-apps.script",
   "description": "",
   "labels": {
    "starred": false,
    "hidden": false,
    "trashed": true,
    "restricted": false,
    "viewed": true
   },
   "createdDate": "2013-06-11T19:24:45.188Z",
   "modifiedDate": "2013-06-11T19:24:58.426Z",
   "modifiedByMeDate": "2013-06-11T19:24:58.426Z",
   "lastViewedByMeDate": "2013-06-11T19:24:58.426Z",
   "parents": [
    {
     "kind": "drive#parentReference",
     "id": "0APdyIOzo7bWDUk9PVA",
     "selfLink": "https://www.googleapis.com/drive/v2/files/1vi0uwcMdHsRv1YFtgq7XdiTGSdqgjIYpdQNC0A_Udn79LOhH0vYL132D/parents/0APdyIOzo7bWDUk9PVA",
     "parentLink": "https://www.googleapis.com/drive/v2/files/0APdyIOzo7bWDUk9PVA",
     "isRoot": true
    }
   ],
   "exportLinks": {
    "application/json": "https://script.google.com/feeds/download/export?id=1234567890abcefghijklmnopqrstuvwxyz&format=json"
   },
   "userPermission": {
    "kind": "drive#permission",
    "etag": "\"kjsas92/259X2r5DVstv1CcIQTjt_RQPSW8\"",
    "id": "me",
    "selfLink": "https://www.googleapis.com/drive/v2/files/1vi0uwcMdHsRv1YFtgq7XdiTGSdqgjIYpdQNC0A_Udn79LOhH0vYL132D/permissions/me",
    "role": "owner",
    "type": "user"
   },
   "quotaBytesUsed": "0",
   "ownerNames": [
    "John Doe"
   ],
   "owners": [
    {
     "kind": "drive#user",
     "displayName": "John Doe",
     "picture": {
      "url": "https://lh4.googleusercontent.com/-yd1rIb6Pe2Y/AAAAAAAAAAI/AAAAAAAAAGs/PP5vTuZonik/s64/photo.jpg"
     },
     "isAuthenticatedUser": true,
     "permissionId": "1234566789"
    }
   ],
   "lastModifyingUserName": "John Doe",
   "lastModifyingUser": {
    "kind": "drive#user",
    "displayName": "John Doe",
    "picture": {
     "url": "https://lh4.googleusercontent.com/-yd1rIb6Pe2Y/AAAAAAAAAAI/AAAAAAAAAGs/PP5vTuZonik/s64/photo.jpg"
    },
    "isAuthenticatedUser": true,
    "permissionId": "1234566789"
   },
   "editable": true,
   "writersCanShare": true,
   "shared": false,
   "explicitlyTrashed": true,
   "appDataContents": false
  }
 ]
}

Apps Script 프로젝트의 파일 ID를 알고 있다면 다음 API 호출을 사용하여 파일을 직접 가져올 수 있습니다.

GET https://www.googleapis.com/drive/v2/files/1234567890abcefghijklmnopqrstuvwxyz
Authorization:  Bearer ya29.fakebearerstring

Drive에서 프로젝트 내보내기

API에서 File 리소스를 가져오면 exportLinks 속성에 프로젝트의 콘텐츠를 JSON 데이터로 가져오기 위해 가져올 URL이 포함됩니다. 다음은 이 URL의 샘플입니다.

https://script.google.com/feeds/download/export?id=1234567890abcefghijklmnopqrstuvwxyz&format=json

이 URL에 요청하여 프로젝트 자체의 콘텐츠를 가져옵니다. 동일한 OAuth Bearer 토큰이 포함된 Authorization 헤더를 포함해야 합니다.

다음은 샘플 요청 및 응답입니다.

GET https://script.google.com/feeds/download/export?id=1234567890abcefghijklmnopqrstuvwxyz&format=json
Authorization:  Bearer ya29.fakebearerstring
{
  "files": [
    {
      "id":"9basdfbd-749a-4as9b-b9d1-d64basdf803",
      "name":"Code",
      "type":"server_js",
      "source":"function doGet() {\n  return HtmlService.createHtmlOutputFromFile(\u0027index\u0027);\n}\n"
    },
    {
      "id":"3asf7c0d-1afb-4a9-8431-5asdfc79e7ae",
      "name":"index",
      "type":"html",
      "source":"\u003chtml\u003e\n  \u003cbody\u003e\n    Hello, world!\n  \u003c/body\u003e\n\u003c/html\u003e"
    }
  ]
}

위의 예에는 HTML 서비스 가이드의 간단한 웹 앱 코드가 포함되어 있습니다. 각각 다음 4가지 속성(
)이 있는 Files 배열이 반환됩니다.

id 프로젝트 내 파일의 내부 식별자로, 업데이트 중에 이 파일을 참조하는 데 필요합니다.
name 스크립트 편집기에 표시되는 확장자가 없는 파일 이름입니다.
type 두 가지 파일 유형은 server_js와 html입니다.
source 파일에 포함된 인코딩된 소스 코드입니다.

Drive로 프로젝트 가져오기

기존 프로젝트를 업데이트하려면 적절한 fileId를 사용하여 update API 파일에 HTTP PUT를 호출합니다. 아래 예는 미디어 업로드 부분의 샘플 트랜잭션을 보여줍니다. 클라이언트 라이브러리 중 하나를 사용하면 애플리케이션에서 동일한 업로드 호출에 메타데이터와 미디어를 쉽게 포함할 수 있습니다. 이 경우 Content-Type 헤더는 업로드된 콘텐츠의 유형을 지정합니다.

PUT https://www.googleapis.com/upload/drive/v2/files/1234567890abcefghijklmnopqrstuvwxyz
Authorization:  Bearer ya29.fakebearerestring
Content-Type:  application/vnd.google-apps.script+json
{
  "files": [
    {
      "id":"9basdfbd-749a-4as9b-b9d1-d64basdf803",
      "name":"Code",
      "type":"server_js",
      "source":"function doGet() {\n  return HtmlService.createHtmlOutputFromFile(\u0027index\u0027);\n}\n"
    },
    {
      "id":"3asf7c0d-1afb-4a9-8431-5asdfc79e7ae",
      "name":"index",
      "type":"html",
      "source":"\u003chtml\u003e\n  \u003cbody\u003e\n    New message!!\n  \u003c/body\u003e\n\u003c/html\u003e"
    }
  ]
}

프로젝트 내에 새 파일 만들기

프로젝트 내에 새 파일을 만들려면 id 속성이 없는 파일에 관한 PUT 요청을 보냅니다. 알 수 없는 식별자가 있는 파일을 포함하면 시스템에서 오류 메시지를 발생시킵니다.

프로젝트 내 파일 삭제

프로젝트에서 파일을 삭제하려면 해당 파일이 포함되지 않지만 프로젝트의 다른 모든 파일이 포함된 PUT 요청을 전송합니다. 가져오기 프로세스 중에 다시 전송되지 않은 파일은 서버에서 삭제됩니다.

프로젝트 내 파일 이름 변경하기

프로젝트 내에서 파일 이름을 바꾸려면 기존 id이지만 새 name가 포함된 PUT 요청을 전송합니다. 서버는 type로 변경하려는 시도를 무시합니다.

새 프로젝트 만들기

새 프로젝트를 만들려면 POST 요청을 파일 insert API로 전송합니다. update 호출과 마찬가지로 클라이언트 라이브러리를 사용하여 프로젝트 이름 및 설명과 같은 메타데이터를 포함할 수 있습니다.

다음은 미디어 업로드의 샘플 거래입니다. 이렇게 하면 Drive에 'Untitled'라는 프로젝트가 생성됩니다. URL의 convert 매개변수는 필수 항목입니다. update 호출과 마찬가지로 Content-Type 헤더가 필요합니다.

POST https://www.googleapis.com/upload/drive/v2/files?convert=true
Authorization:  Bearer ya29.fakebearerestring
Content-Type:  application/vnd.google-apps.script+json
{
  "files": [
    {
      "name":"Code",
      "type":"server_js",
      "source":"function doGet() {\n  return HtmlService.createHtmlOutputFromFile(\u0027index\u0027);\n}\n"
    },
    {
      "name":"index",
      "type":"html",
      "source":"\u003chtml\u003e\n  \u003cbody\u003e\n    Hello, world!!\n  \u003c/body\u003e\n\u003c/html\u003e"
    }
  ]
}