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

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

예를 들어 개발자는 자신이 좋아하는 코드 편집기를 사용하여 로컬 머신에서 새 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. 서버 측 스크립트 파일에는 유효한 자바스크립트가 포함되어야 합니다. 서버 .js 파일에 오류가 있으면 Google Drive API 업데이트 호출이 5xx 오류와 함께 실패합니다. 가져오기 전에 코드를 린트하면 이를 방지할 수 있습니다.
  5. 빈 파일은 가져올 수 없습니다. 빈 파일을 업로드하려고 하면 Google Drive API 업데이트 호출이 5xx 오류와 함께 실패합니다.
  6. 독립형 스크립트만 가져오거나 내보낼 수 있습니다. 컨테이너 결합 스크립트는 Google Drive API를 통해 액세스할 수 없습니다.
  7. 소스 코드만 가져오거나 내보낼 수 있습니다. 프로젝트 속성이나 로그와 같은 리소스도 Google Drive API를 통해 노출되지 않습니다. Google Drive API를 통해서는 스크립트 버전 관리, 게시 또는 실행과 같은 작업이 불가능합니다.
  8. 단일 서버 Code.gs 파일로 제한되지 않습니다. 개발의 용이성을 위해 서버 코드를 여러 파일에 분산할 수 있습니다. 모든 서버 파일은 동일한 전역 네임스페이스에 로드되므로 안전한 캡슐화를 제공하려면 자바스크립트 클래스를 사용하세요.

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

기존 프로젝트 나열

드라이브의 모든 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로 변경하려는 모든 시도를 무시합니다.

새 프로젝트 만들기

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

다음은 미디어 업로드의 샘플 거래입니다. 이렇게 하면 Drive에 '제목 없음'이라는 프로젝트가 만들어집니다 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"
    }
  ]
}