Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions docs/themes.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ zcli themes commands helps with managing Zendesk Help Center theming workflow.
* [`zcli themes:publish`](#zcli-themespublish)
* [`zcli themes:delete`](#zcli-themesdelete)
* [`zcli themes:list`](#zcli-themeslist)
* [`zcli themes:export [THEMEDIRECTORY]`](#zcli-themesexport-themedirectory)

## Configuration

Expand Down Expand Up @@ -147,3 +148,26 @@ EXAMPLES
$ zcli themes:list --brandId=123456
$ zcli themes:list --brandId=123456 --json
```

## `zcli themes:export [THEMEDIRECTORY]`

exports a theme as a zip file

```
USAGE
$ zcli themes:export [THEMEDIRECTORY]

ARGUMENTS
THEMEDIRECTORY [default: .] directory where the exported theme zip is written

OPTIONS
--themeId The id of the theme to export
--json Return JSON output (useful in CI)

EXAMPLES
$ zcli themes:export --themeId=123456789100
$ zcli themes:export ./exports --themeId=123456789100
$ zcli themes:export --themeId=123456789100 --json
```

The exported theme is written to the theme directory (default: current working directory) as `theme_<themeId>.zip`.
48 changes: 48 additions & 0 deletions packages/zcli-themes/src/commands/themes/export.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { Command, Flags, CliUx } from '@oclif/core'
import * as path from 'path'
import * as chalk from 'chalk'
import createThemeExportJob from '../../lib/createThemeExportJob'
import pollJobStatus from '../../lib/pollJobStatus'
import downloadThemePackage from '../../lib/downloadThemePackage'

export default class Export extends Command {
static description = 'export a theme'

static enableJsonFlag = true

static flags = {
themeId: Flags.string({ description: 'The id of the theme to export' })
}

static args = [
{ name: 'themeDirectory', required: true, default: '.' }
]
Comment thread
luis-almeida marked this conversation as resolved.
Comment on lines +17 to +19

static examples = [
'$ zcli themes:export --themeId=abcd',
'$ zcli themes:export ./exports --themeId=abcd'
]

static strict = false

async run () {
let { flags: { themeId }, argv: [themeDirectory] } = await this.parse(Export)
const destination = path.resolve(themeDirectory)
Comment on lines +29 to +30

themeId = themeId || await CliUx.ux.prompt('Theme ID')

const job = await createThemeExportJob(themeId)

// The download URL is provided when the job is created; the poll only
// waits for the export to finish (the completed job's `data` is null).
const downloadUrl = job.data.download.url

await pollJobStatus(destination, job.id)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: pollJobStatus says it receives themePath as an argument so probably would make sense to call it that instead of destination


const filePath = await downloadThemePackage(downloadUrl, themeId, destination)

this.log(chalk.green('Theme exported successfully'), `theme ID: ${themeId}`, filePath)

return { themeId, path: filePath }
}
}
63 changes: 63 additions & 0 deletions packages/zcli-themes/src/lib/createThemeExportJob.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import * as sinon from 'sinon'
import { expect } from '@oclif/test'
import * as axios from 'axios'
import { request } from '@zendesk/zcli-core'
import createThemeExportJob from './createThemeExportJob'
import * as chalk from 'chalk'
import * as errors from '@oclif/core/lib/errors'

describe('createThemeExportJob', () => {
beforeEach(() => {
sinon.restore()
})

it('calls the jobs/themes/exports endpoint with the correct payload and returns the job', async () => {
const requestStub = sinon.stub(request, 'requestAPI')
const job = {
id: '9999',
status: 'pending',
data: { download: { url: 'download/url' } }
}

requestStub.returns(Promise.resolve({ data: { job } }) as axios.AxiosPromise)

expect(await createThemeExportJob('1234')).to.equal(job)

expect(requestStub.calledWith('/api/v2/guide/theming/jobs/themes/exports', sinon.match({
method: 'POST',
data: {
job: {
attributes: {
theme_id: '1234',
format: 'zip'
}
}
}
}))).to.equal(true)
})

it('errors when creation fails', async () => {
const errorStub = sinon.stub(errors, 'error').callThrough()

sinon.stub(request, 'requestAPI').throws({
response: {
data: {
errors: [{
code: 'ThemeNotFound',
title: 'Invalid id'
}]
}
}
})

try {
await createThemeExportJob('1234')
throw new Error('Should have thrown an error')
} catch (error) {
if (error instanceof Error && error.message === 'Should have thrown an error') {
throw error
}
expect(errorStub.calledWith(`${chalk.bold('ThemeNotFound')} - Invalid id`)).to.equal(true)
}
Comment thread
luis-almeida marked this conversation as resolved.
})
})
31 changes: 31 additions & 0 deletions packages/zcli-themes/src/lib/createThemeExportJob.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import type { ExportJob } from '../types'
import { CliUx } from '@oclif/core'
import { request } from '@zendesk/zcli-core'
import type { AxiosError } from 'axios'
import handleThemeApiError from './handleThemeApiError'

export default async function createThemeExportJob (themeId: string): Promise<ExportJob> {
CliUx.ux.action.start('Creating theme export job')

try {
const { data: { job } } = await request.requestAPI('/api/v2/guide/theming/jobs/themes/exports', {
method: 'POST',
headers: {
'X-Zendesk-Request-Originator': 'zcli themes:export'
},
data: {
job: {
attributes: {
theme_id: themeId,
format: 'zip'
}
}
},
validateStatus: (status: number) => status === 202
})
CliUx.ux.action.stop('Ok')
return job
} catch (error) {
handleThemeApiError(error as AxiosError)
}
Comment on lines +28 to +30
}
51 changes: 51 additions & 0 deletions packages/zcli-themes/src/lib/downloadThemePackage.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import * as sinon from 'sinon'
import { expect } from '@oclif/test'
import * as axios from 'axios'
import * as fs from 'fs'
import * as path from 'path'
import { request } from '@zendesk/zcli-core'
import downloadThemePackage from './downloadThemePackage'
import * as errors from '@oclif/core/lib/errors'

describe('downloadThemePackage', () => {
beforeEach(() => {
sinon.restore()
})

it('downloads the package from the presigned url and writes it to the destination', async () => {
const requestStub = sinon.stub(request, 'requestRaw')
const mkdirStub = sinon.stub(fs, 'mkdirSync')
const writeFileStub = sinon.stub(fs, 'writeFileSync')

requestStub.returns(Promise.resolve({ data: Buffer.from('theme content') }) as axios.AxiosPromise)

const filePath = await downloadThemePackage('download/url', '1234', '/tmp/exports')

expect(requestStub.calledWith('download/url', sinon.match({
method: 'GET',
responseType: 'arraybuffer'
}))).to.equal(true)

expect(filePath).to.equal(path.join('/tmp/exports', 'theme_1234.zip'))
expect(mkdirStub.calledWith('/tmp/exports', { recursive: true })).to.equal(true)
expect(writeFileStub.calledWith(filePath, sinon.match.instanceOf(Buffer))).to.equal(true)
})

it('errors when the download fails', async () => {
const requestStub = sinon.stub(request, 'requestRaw')
const errorStub = sinon.stub(errors, 'error').callThrough()
const error = new axios.AxiosError('Network error')

requestStub.throws(error)

try {
await downloadThemePackage('download/url', '1234', '/tmp/exports')
throw new Error('Should have thrown an error')
} catch (thrown) {
if (thrown instanceof Error && thrown.message === 'Should have thrown an error') {
throw thrown
}
expect(errorStub.calledWith(error)).to.equal(true)
}
Comment thread
luis-almeida marked this conversation as resolved.
})
})
28 changes: 28 additions & 0 deletions packages/zcli-themes/src/lib/downloadThemePackage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { CliUx } from '@oclif/core'
import { request } from '@zendesk/zcli-core'
import { error } from '@oclif/core/lib/errors'
Comment thread
luis-almeida marked this conversation as resolved.
import type { AxiosError } from 'axios'
import * as fs from 'fs'
import * as path from 'path'

export default async function downloadThemePackage (downloadUrl: string, themeId: string, destination: string): Promise<string> {
CliUx.ux.action.start('Downloading theme package')

const filePath = path.join(destination, `theme_${themeId}.zip`)
Comment thread
luis-almeida marked this conversation as resolved.

try {
// `requestRaw` hits the presigned download URL directly, without the
// Zendesk `Authorization` header or base URL that `requestAPI` adds.
const response = await request.requestRaw(downloadUrl, {
method: 'GET',
responseType: 'arraybuffer',
validateStatus: (status: number) => status === 200
})
fs.mkdirSync(destination, { recursive: true })
fs.writeFileSync(filePath, Buffer.from(response.data))
Comment thread
luis-almeida marked this conversation as resolved.
Comment on lines +21 to +22
Comment on lines +21 to +22
CliUx.ux.action.stop('Ok')
return filePath
} catch (e) {
error(e as AxiosError)
Comment thread
luis-almeida marked this conversation as resolved.
}
}
8 changes: 8 additions & 0 deletions packages/zcli-themes/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,14 @@ export type PendingJob = {
data: JobData
}

export type ExportJob = PendingJob & {
data: {
download: {
url: string
}
}
}

export type CompletedJob = {
id: string,
status: 'completed',
Expand Down
Loading
Loading