From 377dfb8e220276549364094ea9c1a88cdd63f50c Mon Sep 17 00:00:00 2001 From: Lorenzo Alberto Maria Ambrosi Date: Mon, 22 Jun 2020 17:15:55 +0200 Subject: [PATCH 01/12] Split drive selector from target selector Change-type: patch Signed-off-by: Lorenzo Alberto Maria Ambrosi --- .../drive-selector.tsx} | 123 +++++++++++------- .../target-selector-button.tsx | 2 +- .../target-selector/target-selector.tsx} | 24 +++- lib/gui/app/pages/main/Flash.tsx | 8 +- lib/gui/app/pages/main/MainPage.tsx | 7 +- lib/shared/drive-constraints.ts | 2 +- 6 files changed, 104 insertions(+), 62 deletions(-) rename lib/gui/app/components/{target-selector/target-selector-modal.tsx => drive-selector/drive-selector.tsx} (77%) rename lib/gui/app/{pages/main/DriveSelector.tsx => components/target-selector/target-selector.tsx} (89%) diff --git a/lib/gui/app/components/target-selector/target-selector-modal.tsx b/lib/gui/app/components/drive-selector/drive-selector.tsx similarity index 77% rename from lib/gui/app/components/target-selector/target-selector-modal.tsx rename to lib/gui/app/components/drive-selector/drive-selector.tsx index 58b7d004..5523c96b 100644 --- a/lib/gui/app/components/target-selector/target-selector-modal.tsx +++ b/lib/gui/app/components/drive-selector/drive-selector.tsx @@ -33,7 +33,7 @@ import { getDriveImageCompatibilityStatuses, hasListDriveImageCompatibilityStatus, isDriveValid, - TargetStatus, + DriveStatus, Image, } from '../../../../shared/drive-constraints'; import { compatibility } from '../../../../shared/messages'; @@ -49,7 +49,7 @@ import { logEvent, logException } from '../../modules/analytics'; import { open as openExternal } from '../../os/open-external/services/open-external'; import { Modal, ScrollableFlex } from '../../styled-components'; -import TargetSVGIcon from '../../../assets/tgt.svg'; +import DriveSVGIcon from '../../../assets/tgt.svg'; interface UsbbootDrive extends sourceDestination.UsbbootDrive { progress: number; @@ -64,26 +64,26 @@ interface DriverlessDrive { linkCTA: string; } -type Target = scanner.adapters.DrivelistDrive | DriverlessDrive | UsbbootDrive; +type Drive = scanner.adapters.DrivelistDrive | DriverlessDrive | UsbbootDrive; -function isUsbbootDrive(drive: Target): drive is UsbbootDrive { +function isUsbbootDrive(drive: Drive): drive is UsbbootDrive { return (drive as UsbbootDrive).progress !== undefined; } -function isDriverlessDrive(drive: Target): drive is DriverlessDrive { +function isDriverlessDrive(drive: Drive): drive is DriverlessDrive { return (drive as DriverlessDrive).link !== undefined; } function isDrivelistDrive( - drive: Target, + drive: Drive, ): drive is scanner.adapters.DrivelistDrive { return typeof (drive as scanner.adapters.DrivelistDrive).size === 'number'; } -const TargetsTable = styled(({ refFn, ...props }) => { +const DrivesTable = styled(({ refFn, ...props }) => { return (
- ref={refFn} {...props} /> + ref={refFn} {...props} />
); })` @@ -145,30 +145,37 @@ const InitProgress = styled( } `; -interface TargetSelectorModalProps extends Omit { - done: (targets: scanner.adapters.DrivelistDrive[]) => void; +export interface DriveSelectorProps + extends Omit { + multipleSelection?: boolean; + cancel: () => void; + done: (drives: scanner.adapters.DrivelistDrive[]) => void; + titleLabel: string; + emptyListLabel: string; } -interface TargetSelectorModalState { - drives: Target[]; +interface DriveSelectorState { + drives: Drive[]; image: Image; missingDriversModal: { drive?: DriverlessDrive }; selectedList: scanner.adapters.DrivelistDrive[]; showSystemDrives: boolean; } -export class TargetSelectorModal extends React.Component< - TargetSelectorModalProps, - TargetSelectorModalState +export class DriveSelector extends React.Component< + DriveSelectorProps, + DriveSelectorState > { private unsubscribe: (() => void) | undefined; - tableColumns: Array>; + multipleSelection: boolean; + tableColumns: Array>; - constructor(props: TargetSelectorModalProps) { + constructor(props: DriveSelectorProps) { super(props); const defaultMissingDriversModalState: { drive?: DriverlessDrive } = {}; const selectedList = getSelectedDrives(); + this.multipleSelection = !!this.props.multipleSelection; this.state = { drives: getDrives(), @@ -182,7 +189,7 @@ export class TargetSelectorModal extends React.Component< { field: 'description', label: 'Name', - render: (description: string, drive: Target) => { + render: (description: string, drive: Drive) => { return isDrivelistDrive(drive) && drive.isSystem ? ( @@ -197,7 +204,7 @@ export class TargetSelectorModal extends React.Component< field: 'description', key: 'size', label: 'Size', - render: (_description: string, drive: Target) => { + render: (_description: string, drive: Drive) => { if (isDrivelistDrive(drive) && drive.size !== null) { return bytesToClosestUnit(drive.size); } @@ -207,7 +214,7 @@ export class TargetSelectorModal extends React.Component< field: 'description', key: 'link', label: 'Location', - render: (_description: string, drive: Target) => { + render: (_description: string, drive: Drive) => { return ( {drive.displayName} @@ -231,7 +238,7 @@ export class TargetSelectorModal extends React.Component< key: 'extra', // Space as empty string would use the field name as label label: ' ', - render: (_description: string, drive: Target) => { + render: (_description: string, drive: Drive) => { if (isUsbbootDrive(drive)) { return this.renderProgress(drive.progress); } else if (isDrivelistDrive(drive)) { @@ -244,7 +251,7 @@ export class TargetSelectorModal extends React.Component< ]; } - private driveShouldBeDisabled(drive: Target, image: any) { + private driveShouldBeDisabled(drive: Drive, image: any) { return ( isUsbbootDrive(drive) || isDriverlessDrive(drive) || @@ -252,8 +259,8 @@ export class TargetSelectorModal extends React.Component< ); } - private getDisplayedTargets(targets: Target[]): Target[] { - return targets.filter((drive) => { + private getDisplayedDrives(drives: Drive[]): Drive[] { + return drives.filter((drive) => { return ( isUsbbootDrive(drive) || isDriverlessDrive(drive) || @@ -264,7 +271,7 @@ export class TargetSelectorModal extends React.Component< }); } - private getDisabledTargets(drives: Target[], image: any): string[] { + private getDisabledDrives(drives: Drive[], image: any): string[] { return drives .filter((drive) => this.driveShouldBeDisabled(drive, image)) .map((drive) => drive.displayName); @@ -279,7 +286,7 @@ export class TargetSelectorModal extends React.Component< ); } - private renderStatuses(statuses: TargetStatus[]) { + private renderStatuses(statuses: DriveStatus[]) { return ( // the column render fn expects a single Element <> @@ -324,12 +331,12 @@ export class TargetSelectorModal extends React.Component< const { cancel, done, ...props } = this.props; const { selectedList, drives, image, missingDriversModal } = this.state; - const displayedTargets = this.getDisplayedTargets(drives); - const disabledTargets = this.getDisabledTargets(drives, image); + const displayedDrives = this.getDisplayedDrives(drives); + const disabledDrives = this.getDisabledDrives(drives, image); const numberOfSystemDrives = drives.filter( (drive) => isDrivelistDrive(drive) && drive.isSystem, ).length; - const numberOfDisplayedSystemDrives = displayedTargets.filter( + const numberOfDisplayedSystemDrives = displayedDrives.filter( (drive) => isDrivelistDrive(drive) && drive.isSystem, ).length; const numberOfHiddenSystemDrives = @@ -341,7 +348,7 @@ export class TargetSelectorModal extends React.Component< titleElement={ - Select target + {this.props.titleLabel} - - Plug a target drive + + {this.props.emptyListLabel} ) : ( - - ) => { + + ) => { if (t !== null) { t.setRowSelection(selectedList); } }} columns={this.tableColumns} - data={displayedTargets} - disabledRows={disabledTargets} + data={displayedDrives} + disabledRows={disabledDrives} rowKey="displayName" - onCheck={(rows: Target[]) => { + onCheck={(rows: Drive[]) => { + const newSelection = rows.filter(isDrivelistDrive); + if (this.multipleSelection) { + this.setState({ + selectedList: newSelection, + }); + return; + } this.setState({ - selectedList: rows.filter(isDrivelistDrive), + selectedList: newSelection.slice(newSelection.length - 1), }); }} - onRowClick={(row: Target) => { + onRowClick={(row: Drive) => { if ( !isDrivelistDrive(row) || this.driveShouldBeDisabled(row, image) ) { return; } - const newList = [...selectedList]; - const selectedIndex = selectedList.findIndex( - (target) => target.device === row.device, - ); - if (selectedIndex === -1) { - newList.push(row); - } else { - // Deselect if selected - newList.splice(selectedIndex, 1); + if (this.multipleSelection) { + const newList = [...selectedList]; + const selectedIndex = selectedList.findIndex( + (drive) => drive.device === row.device, + ); + if (selectedIndex === -1) { + newList.push(row); + } else { + // Deselect if selected + newList.splice(selectedIndex, 1); + } + this.setState({ + selectedList: newList, + }); + return; } this.setState({ - selectedList: newList, + selectedList: [row], }); }} /> diff --git a/lib/gui/app/components/target-selector/target-selector-button.tsx b/lib/gui/app/components/target-selector/target-selector-button.tsx index e6bd6424..f7abd371 100644 --- a/lib/gui/app/components/target-selector/target-selector-button.tsx +++ b/lib/gui/app/components/target-selector/target-selector-button.tsx @@ -67,7 +67,7 @@ function DriveCompatibilityWarning({ ); } -export function TargetSelector(props: TargetSelectorProps) { +export function TargetSelectorButton(props: TargetSelectorProps) { const targets = getSelectedDrives(); if (targets.length === 1) { diff --git a/lib/gui/app/pages/main/DriveSelector.tsx b/lib/gui/app/components/target-selector/target-selector.tsx similarity index 89% rename from lib/gui/app/pages/main/DriveSelector.tsx rename to lib/gui/app/components/target-selector/target-selector.tsx index f89e4d98..958e99f9 100644 --- a/lib/gui/app/pages/main/DriveSelector.tsx +++ b/lib/gui/app/components/target-selector/target-selector.tsx @@ -19,6 +19,10 @@ import * as React from 'react'; import { Flex } from 'rendition'; import { TargetSelector } from '../../components/target-selector/target-selector-button'; import { TargetSelectorModal } from '../../components/target-selector/target-selector-modal'; +import { + DriveSelector, + DriveSelectorProps, +} from '../drive-selector/drive-selector'; import { isDriveSelected, getImage, @@ -50,6 +54,16 @@ const getDriveSelectionStateSlice = () => ({ image: getImage(), }); +export const TargetSelectorModal = ( + props: Omit, +) => ( + +); + export const selectAllTargets = ( modalTargets: scanner.adapters.DrivelistDrive[], ) => { @@ -79,17 +93,17 @@ export const selectAllTargets = ( }); }; -interface DriveSelectorProps { +interface TargetSelectorProps { disabled: boolean; hasDrive: boolean; flashing: boolean; } -export const DriveSelector = ({ +export const TargetSelector = ({ disabled, hasDrive, flashing, -}: DriveSelectorProps) => { +}: TargetSelectorProps) => { // TODO: inject these from redux-connector const [ { showDrivesButton, driveListLabel, targets, image }, @@ -115,7 +129,7 @@ export const DriveSelector = ({ }} /> - + /> )} ); diff --git a/lib/gui/app/pages/main/Flash.tsx b/lib/gui/app/pages/main/Flash.tsx index 24c6e9c6..b61853d4 100644 --- a/lib/gui/app/pages/main/Flash.tsx +++ b/lib/gui/app/pages/main/Flash.tsx @@ -24,7 +24,6 @@ import * as constraints from '../../../../shared/drive-constraints'; import * as messages from '../../../../shared/messages'; import { ProgressButton } from '../../components/progress-button/progress-button'; import { SourceOptions } from '../../components/source-selector/source-selector'; -import { TargetSelectorModal } from '../../components/target-selector/target-selector-modal'; import * as availableDrives from '../../models/available-drives'; import * as flashState from '../../models/flash-state'; import * as selection from '../../models/selection-state'; @@ -32,7 +31,10 @@ import * as analytics from '../../modules/analytics'; import { scanner as driveScanner } from '../../modules/drive-scanner'; import * as imageWriter from '../../modules/image-writer'; import * as notification from '../../os/notification'; -import { selectAllTargets } from './DriveSelector'; +import { + selectAllTargets, + TargetSelectorModal, +} from '../../components/target-selector/target-selector'; import FlashSvg from '../../../assets/flash.svg'; @@ -333,7 +335,7 @@ export class FlashStep extends React.PureComponent< selectAllTargets(modalTargets); this.setState({ showDriveSelectorModal: false }); }} - > + /> )} ); diff --git a/lib/gui/app/pages/main/MainPage.tsx b/lib/gui/app/pages/main/MainPage.tsx index d4577175..e2306540 100644 --- a/lib/gui/app/pages/main/MainPage.tsx +++ b/lib/gui/app/pages/main/MainPage.tsx @@ -44,7 +44,10 @@ import { import { bytesToClosestUnit } from '../../../../shared/units'; -import { DriveSelector, getDriveListLabel } from './DriveSelector'; +import { + TargetSelector, + getDriveListLabel, +} from '../../components/target-selector/target-selector'; import { FlashStep } from './Flash'; import EtcherSvg from '../../../assets/etcher.svg'; @@ -252,7 +255,7 @@ export class MainPage extends React.Component< - Date: Mon, 22 Jun 2020 17:16:41 +0200 Subject: [PATCH 02/12] Add clone-drive workflow Change-type: patch Changelog-entry: Add clone-drive workflow Signed-off-by: Lorenzo Alberto Maria Ambrosi --- .../drive-selector/drive-selector.tsx | 13 +- .../source-selector/source-selector.tsx | 403 ++++++++++-------- lib/gui/app/models/available-drives.ts | 2 +- lib/gui/app/models/selection-state.ts | 12 +- lib/gui/app/models/store.ts | 32 +- lib/gui/app/modules/image-writer.ts | 27 +- lib/gui/app/pages/main/Flash.tsx | 7 +- lib/gui/app/pages/main/MainPage.tsx | 28 +- lib/gui/modules/child-writer.ts | 35 +- lib/shared/drive-constraints.ts | 31 +- lib/shared/messages.ts | 4 +- tests/gui/models/available-drives.spec.ts | 2 +- tests/gui/models/selection-state.spec.ts | 44 +- tests/gui/modules/image-writer.spec.ts | 50 +-- tests/shared/drive-constraints.spec.ts | 31 ++ 15 files changed, 389 insertions(+), 332 deletions(-) diff --git a/lib/gui/app/components/drive-selector/drive-selector.tsx b/lib/gui/app/components/drive-selector/drive-selector.tsx index 5523c96b..cdcb374f 100644 --- a/lib/gui/app/components/drive-selector/drive-selector.tsx +++ b/lib/gui/app/components/drive-selector/drive-selector.tsx @@ -167,7 +167,7 @@ export class DriveSelector extends React.Component< DriveSelectorState > { private unsubscribe: (() => void) | undefined; - multipleSelection: boolean; + multipleSelection: boolean = true; tableColumns: Array>; constructor(props: DriveSelectorProps) { @@ -175,7 +175,11 @@ export class DriveSelector extends React.Component< const defaultMissingDriversModalState: { drive?: DriverlessDrive } = {}; const selectedList = getSelectedDrives(); - this.multipleSelection = !!this.props.multipleSelection; + const multipleSelection = this.props.multipleSelection; + this.multipleSelection = + multipleSelection !== undefined + ? !!multipleSelection + : this.multipleSelection; this.state = { drives: getDrives(), @@ -383,10 +387,7 @@ export class DriveSelector extends React.Component< {this.props.emptyListLabel} ) : ( - + ) => { if (t !== null) { diff --git a/lib/gui/app/components/source-selector/source-selector.tsx b/lib/gui/app/components/source-selector/source-selector.tsx index 7d8fa78f..69738224 100644 --- a/lib/gui/app/components/source-selector/source-selector.tsx +++ b/lib/gui/app/components/source-selector/source-selector.tsx @@ -14,10 +14,11 @@ * limitations under the License. */ +import CopySvg from '@fortawesome/fontawesome-free/svgs/solid/copy.svg'; import FileSvg from '@fortawesome/fontawesome-free/svgs/solid/file.svg'; import LinkSvg from '@fortawesome/fontawesome-free/svgs/solid/link.svg'; import ExclamationTriangleSvg from '@fortawesome/fontawesome-free/svgs/solid/exclamation-triangle.svg'; -import { sourceDestination } from 'etcher-sdk'; +import { sourceDestination, scanner } from 'etcher-sdk'; import { ipcRenderer, IpcRendererEvent } from 'electron'; import * as _ from 'lodash'; import { GPTPartition, MBRPartition } from 'partitioninfo'; @@ -57,6 +58,7 @@ import { middleEllipsis } from '../../utils/middle-ellipsis'; import { SVGIcon } from '../svg-icon/svg-icon'; import ImageSvg from '../../../assets/image.svg'; +import { DriveSelector } from '../drive-selector/drive-selector'; const recentUrlImagesKey = 'recentUrlImages'; @@ -92,6 +94,9 @@ function setRecentUrlImages(urls: URL[]) { localStorage.setItem(recentUrlImagesKey, JSON.stringify(normalized)); } +const isURL = (imagePath: string) => + imagePath.startsWith('https://') || imagePath.startsWith('http://'); + const Card = styled(BaseCard)` hr { margin: 5px 0; @@ -117,6 +122,10 @@ function getState() { }; } +function isString(value: any): value is string { + return typeof value === 'string'; +} + const URLSelector = ({ done, cancel, @@ -203,7 +212,12 @@ interface Flow { const FlowSelector = styled( ({ flow, ...props }: { flow: Flow; props?: ButtonProps }) => { return ( - + flow.onClick(evt)} + icon={flow.icon} + {...props} + > {flow.label} ); @@ -225,16 +239,20 @@ const FlowSelector = styled( export type Source = | typeof sourceDestination.File + | typeof sourceDestination.BlockDevice | typeof sourceDestination.Http; -export interface SourceOptions { - imagePath: string; +export interface SourceMetadata extends sourceDestination.Metadata { + hasMBR: boolean; + partitions: MBRPartition[] | GPTPartition[]; + path: string; SourceType: Source; + drive?: scanner.adapters.DrivelistDrive; + extension?: string; } interface SourceSelectorProps { flashing: boolean; - afterSelected: (options: SourceOptions) => void; } interface SourceSelectorState { @@ -244,6 +262,7 @@ interface SourceSelectorState { warning: { message: string; title: string | null } | null; showImageDetails: boolean; showURLSelector: boolean; + showDriveSelector: boolean; } export class SourceSelector extends React.Component< @@ -251,7 +270,6 @@ export class SourceSelector extends React.Component< SourceSelectorState > { private unsubscribe: (() => void) | undefined; - private afterSelected: SourceSelectorProps['afterSelected']; constructor(props: SourceSelectorProps) { super(props); @@ -260,15 +278,8 @@ export class SourceSelector extends React.Component< warning: null, showImageDetails: false, showURLSelector: false, + showDriveSelector: false, }; - - this.openImageSelector = this.openImageSelector.bind(this); - this.openURLSelector = this.openURLSelector.bind(this); - this.reselectImage = this.reselectImage.bind(this); - this.onSelectImage = this.onSelectImage.bind(this); - this.onDrop = this.onDrop.bind(this); - this.showSelectedImageDetails = this.showSelectedImageDetails.bind(this); - this.afterSelected = props.afterSelected.bind(this); } public componentDidMount() { @@ -285,15 +296,28 @@ export class SourceSelector extends React.Component< } private async onSelectImage(_event: IpcRendererEvent, imagePath: string) { - const isURL = - imagePath.startsWith('https://') || imagePath.startsWith('http://'); - await this.selectImageByPath({ + await this.selectSource( imagePath, - SourceType: isURL ? sourceDestination.Http : sourceDestination.File, - }).promise; + isURL(imagePath) ? sourceDestination.Http : sourceDestination.File, + ).promise; } - private reselectImage() { + private async createSource(selected: string, SourceType: Source) { + try { + selected = await replaceWindowsNetworkDriveLetter(selected); + } catch (error) { + analytics.logException(error); + } + + if (SourceType === sourceDestination.File) { + return new sourceDestination.File({ + path: selected, + }); + } + return new sourceDestination.Http({ url: selected }); + } + + private reselectSource() { analytics.logEvent('Reselect image', { previousImage: selectionState.getImage(), }); @@ -301,144 +325,134 @@ export class SourceSelector extends React.Component< selectionState.deselectImage(); } - private selectImage( - image: sourceDestination.Metadata & { - path: string; - extension: string; - hasMBR: boolean; - }, - ) { - try { - let message = null; - let title = null; - - if (supportedFormats.looksLikeWindowsImage(image.path)) { - analytics.logEvent('Possibly Windows image', { image }); - message = messages.warning.looksLikeWindowsImage(); - title = 'Possible Windows image detected'; - } else if (!image.hasMBR) { - analytics.logEvent('Missing partition table', { image }); - title = 'Missing partition table'; - message = messages.warning.missingPartitionTable(); - } - - if (message) { - this.setState({ - warning: { - message, - title, - }, - }); - } - - selectionState.selectImage(image); - analytics.logEvent('Select image', { - // An easy way so we can quickly identify if we're making use of - // certain features without printing pages of text to DevTools. - image: { - ...image, - logo: Boolean(image.logo), - blockMap: Boolean(image.blockMap), - }, - }); - } catch (error) { - exceptionReporter.report(error); - } - } - - private selectImageByPath({ - imagePath, - SourceType, - }: SourceOptions): { promise: Promise; cancel: () => void } { + private selectSource( + selected: string | scanner.adapters.DrivelistDrive, + SourceType: Source, + ): { promise: Promise; cancel: () => void } { let cancelled = false; return { cancel: () => { cancelled = true; }, promise: (async () => { - try { - imagePath = await replaceWindowsNetworkDriveLetter(imagePath); - } catch (error) { - analytics.logException(error); - } - if (cancelled) { - return; - } - - let source; - if (SourceType === sourceDestination.File) { - source = new sourceDestination.File({ - path: imagePath, - }); - } else { - if ( - !imagePath.startsWith('https://') && - !imagePath.startsWith('http://') - ) { - const invalidImageError = errors.createUserError({ - title: 'Unsupported protocol', - description: messages.error.unsupportedProtocol(), - }); - - osDialog.showError(invalidImageError); - analytics.logEvent('Unsupported protocol', { path: imagePath }); - return; - } - source = new sourceDestination.Http({ url: imagePath }); - } - - try { - const innerSource = await source.getInnerSource(); + const sourcePath = isString(selected) ? selected : selected.device; + let metadata: SourceMetadata | undefined; + if (isString(selected)) { + const source = await this.createSource(selected, SourceType); if (cancelled) { return; } - const metadata = (await innerSource.getMetadata()) as sourceDestination.Metadata & { - hasMBR: boolean; - partitions: MBRPartition[] | GPTPartition[]; - path: string; - extension: string; - }; - if (cancelled) { - return; - } - const partitionTable = await innerSource.getPartitionTable(); - if (cancelled) { - return; - } - if (partitionTable) { - metadata.hasMBR = true; - metadata.partitions = partitionTable.partitions; - } else { - metadata.hasMBR = false; - } - metadata.path = imagePath; - metadata.extension = path.extname(imagePath).slice(1); - this.selectImage(metadata); - this.afterSelected({ - imagePath, - SourceType, - }); - } catch (error) { - const imageError = errors.createUserError({ - title: 'Error opening image', - description: messages.error.openImage( - path.basename(imagePath), - error.message, - ), - }); - osDialog.showError(imageError); - analytics.logException(error); - } finally { try { - await source.close(); + const innerSource = await source.getInnerSource(); + if (cancelled) { + return; + } + metadata = await this.getMetadata(innerSource); + if (cancelled) { + return; + } + if (SourceType === sourceDestination.Http && !isURL(selected)) { + this.handleError( + 'Unsupported protocol', + selected, + messages.error.unsupportedProtocol(), + ); + return; + } + if (supportedFormats.looksLikeWindowsImage(selected)) { + analytics.logEvent('Possibly Windows image', { image: selected }); + this.setState({ + warning: { + message: messages.warning.looksLikeWindowsImage(), + title: 'Possible Windows image detected', + }, + }); + } + metadata.extension = path.extname(selected).slice(1); + metadata.path = selected; + + if (!metadata.hasMBR) { + analytics.logEvent('Missing partition table', { metadata }); + this.setState({ + warning: { + message: messages.warning.missingPartitionTable(), + title: 'Missing partition table', + }, + }); + } } catch (error) { - // Noop + this.handleError( + 'Error opening source', + sourcePath, + messages.error.openSource(sourcePath, error.message), + error, + ); + } finally { + try { + await source.close(); + } catch (error) { + // Noop + } } + } else { + metadata = { + path: selected.device, + size: selected.size as SourceMetadata['size'], + hasMBR: false, + partitions: [], + SourceType: sourceDestination.BlockDevice, + drive: selected, + }; + } + + if (metadata !== undefined) { + selectionState.selectSource(metadata); + analytics.logEvent('Select image', { + // An easy way so we can quickly identify if we're making use of + // certain features without printing pages of text to DevTools. + image: { + ...metadata, + logo: Boolean(metadata.logo), + blockMap: Boolean(metadata.blockMap), + }, + }); } })(), }; } + private handleError( + title: string, + sourcePath: string, + description: string, + error?: any, + ) { + const imageError = errors.createUserError({ + title, + description, + }); + osDialog.showError(imageError); + if (error) { + analytics.logException(error); + return; + } + analytics.logEvent(title, { path: sourcePath }); + } + + private async getMetadata( + source: sourceDestination.SourceDestination | sourceDestination.BlockDevice, + ) { + const metadata = (await source.getMetadata()) as SourceMetadata; + const partitionTable = await source.getPartitionTable(); + if (partitionTable) { + metadata.hasMBR = true; + metadata.partitions = partitionTable.partitions; + } else { + metadata.hasMBR = false; + } + return metadata; + } + private async openImageSelector() { analytics.logEvent('Open image selector'); @@ -450,10 +464,7 @@ export class SourceSelector extends React.Component< analytics.logEvent('Image selector closed'); return; } - await this.selectImageByPath({ - imagePath, - SourceType: sourceDestination.File, - }).promise; + await this.selectSource(imagePath, sourceDestination.File).promise; } catch (error) { exceptionReporter.report(error); } @@ -462,10 +473,7 @@ export class SourceSelector extends React.Component< private async onDrop(event: React.DragEvent) { const [file] = event.dataTransfer.files; if (file) { - await this.selectImageByPath({ - imagePath: file.path, - SourceType: sourceDestination.File, - }).promise; + await this.selectSource(file.path, sourceDestination.File).promise; } } @@ -477,6 +485,14 @@ export class SourceSelector extends React.Component< }); } + private openDriveSelector() { + analytics.logEvent('Open drive selector'); + + this.setState({ + showDriveSelector: true, + }); + } + private onDragOver(event: React.DragEvent) { // Needed to get onDrop events on div elements event.preventDefault(); @@ -500,27 +516,35 @@ export class SourceSelector extends React.Component< // TODO add a visual change when dragging a file over the selector public render() { const { flashing } = this.props; - const { showImageDetails, showURLSelector } = this.state; + const { showImageDetails, showURLSelector, showDriveSelector } = this.state; - const hasImage = selectionState.hasImage(); + const hasSource = selectionState.hasImage(); + let image = hasSource ? selectionState.getImage() : {}; + + image = image.drive ? image.drive : image; - const imagePath = selectionState.getImagePath(); - const imageBasename = hasImage ? path.basename(imagePath) : ''; - const imageName = selectionState.getImageName(); - const imageSize = selectionState.getImageSize(); - const imageLogo = selectionState.getImageLogo(); let cancelURLSelection = () => { // noop }; + image.name = image.description || image.name; + const imagePath = image.path || ''; + const imageBasename = path.basename(image.path || ''); + const imageName = image.name || ''; + const imageSize = image.size || ''; + const imageLogo = image.logo || ''; return ( <> ) => this.onDrop(evt)} + onDragEnter={(evt: React.DragEvent) => + this.onDragEnter(evt) + } + onDragOver={(evt: React.DragEvent) => + this.onDragOver(evt) + } > - {hasImage ? ( + {hasSource ? ( <> this.showSelectedImageDetails()} tooltip={imageName || imageBasename} > {middleEllipsis(imageName || imageBasename, 20)} {!flashing && ( - + this.reselectSource()} + > Remove )} @@ -551,7 +579,7 @@ export class SourceSelector extends React.Component< this.openImageSelector(), label: 'Flash from file', icon: , }} @@ -559,11 +587,19 @@ export class SourceSelector extends React.Component< this.openURLSelector(), label: 'Flash from URL', icon: , }} /> + this.openDriveSelector(), + label: 'Clone drive', + icon: , + }} + /> )} @@ -579,7 +615,7 @@ export class SourceSelector extends React.Component< action="Continue" cancel={() => { this.setState({ warning: null }); - this.reselectImage(); + this.reselectSource(); }} done={() => { this.setState({ warning: null }); @@ -625,13 +661,10 @@ export class SourceSelector extends React.Component< analytics.logEvent('URL selector closed'); } else { let promise; - ({ - promise, - cancel: cancelURLSelection, - } = this.selectImageByPath({ - imagePath: imageURL, - SourceType: sourceDestination.Http, - })); + ({ promise, cancel: cancelURLSelection } = this.selectSource( + imageURL, + sourceDestination.Http, + )); await promise; } this.setState({ @@ -640,6 +673,32 @@ export class SourceSelector extends React.Component< }} /> )} + + {showDriveSelector && ( + { + this.setState({ + showDriveSelector: false, + }); + }} + done={async (drives: scanner.adapters.DrivelistDrive[]) => { + if (!drives.length) { + analytics.logEvent('Drive selector closed'); + this.setState({ + showDriveSelector: false, + }); + return; + } + await this.selectSource(drives[0], sourceDestination.BlockDevice); + this.setState({ + showDriveSelector: false, + }); + }} + /> + )} ); } diff --git a/lib/gui/app/models/available-drives.ts b/lib/gui/app/models/available-drives.ts index f9b77df9..6389886f 100644 --- a/lib/gui/app/models/available-drives.ts +++ b/lib/gui/app/models/available-drives.ts @@ -24,7 +24,7 @@ export function hasAvailableDrives() { export function setDrives(drives: any[]) { store.dispatch({ - type: Actions.SET_AVAILABLE_DRIVES, + type: Actions.SET_AVAILABLE_TARGETS, data: drives, }); } diff --git a/lib/gui/app/models/selection-state.ts b/lib/gui/app/models/selection-state.ts index 232c3de3..6843e256 100644 --- a/lib/gui/app/models/selection-state.ts +++ b/lib/gui/app/models/selection-state.ts @@ -24,7 +24,7 @@ import { Actions, store } from './store'; */ export function selectDrive(driveDevice: string) { store.dispatch({ - type: Actions.SELECT_DRIVE, + type: Actions.SELECT_TARGET, data: driveDevice, }); } @@ -40,10 +40,10 @@ export function toggleDrive(driveDevice: string) { } } -export function selectImage(image: any) { +export function selectSource(source: any) { store.dispatch({ - type: Actions.SELECT_IMAGE, - data: image, + type: Actions.SELECT_SOURCE, + data: source, }); } @@ -122,14 +122,14 @@ export function hasImage(): boolean { */ export function deselectDrive(driveDevice: string) { store.dispatch({ - type: Actions.DESELECT_DRIVE, + type: Actions.DESELECT_TARGET, data: driveDevice, }); } export function deselectImage() { store.dispatch({ - type: Actions.DESELECT_IMAGE, + type: Actions.DESELECT_SOURCE, data: {}, }); } diff --git a/lib/gui/app/models/store.ts b/lib/gui/app/models/store.ts index fe1b3fff..0a1ac58b 100644 --- a/lib/gui/app/models/store.ts +++ b/lib/gui/app/models/store.ts @@ -80,15 +80,15 @@ export const DEFAULT_STATE = Immutable.fromJS({ export enum Actions { SET_DEVICE_PATHS, SET_FAILED_DEVICE_PATHS, - SET_AVAILABLE_DRIVES, + SET_AVAILABLE_TARGETS, SET_FLASH_STATE, RESET_FLASH_STATE, SET_FLASHING_FLAG, UNSET_FLASHING_FLAG, - SELECT_DRIVE, - SELECT_IMAGE, - DESELECT_DRIVE, - DESELECT_IMAGE, + SELECT_TARGET, + SELECT_SOURCE, + DESELECT_TARGET, + DESELECT_SOURCE, SET_APPLICATION_SESSION_UUID, SET_FLASHING_WORKFLOW_UUID, } @@ -116,7 +116,7 @@ function storeReducer( action: Action, ): typeof DEFAULT_STATE { switch (action.type) { - case Actions.SET_AVAILABLE_DRIVES: { + case Actions.SET_AVAILABLE_TARGETS: { // Type: action.data : Array if (!action.data) { @@ -158,7 +158,7 @@ function storeReducer( ) { // Deselect this drive gone from availableDrives return storeReducer(accState, { - type: Actions.DESELECT_DRIVE, + type: Actions.DESELECT_TARGET, data: device, }); } @@ -206,14 +206,14 @@ function storeReducer( ) { // Auto-select this drive return storeReducer(accState, { - type: Actions.SELECT_DRIVE, + type: Actions.SELECT_TARGET, data: drive.device, }); } // Deselect this drive in case it still is selected return storeReducer(accState, { - type: Actions.DESELECT_DRIVE, + type: Actions.DESELECT_TARGET, data: drive.device, }); }, @@ -341,7 +341,7 @@ function storeReducer( .set('flashState', DEFAULT_STATE.get('flashState')); } - case Actions.SELECT_DRIVE: { + case Actions.SELECT_TARGET: { // Type: action.data : String const device = action.data; @@ -391,10 +391,12 @@ function storeReducer( // with image-stream / supported-formats, and have *one* // place where all the image extension / format handling // takes place, to avoid having to check 2+ locations with different logic - case Actions.SELECT_IMAGE: { + case Actions.SELECT_SOURCE: { // Type: action.data : ImageObject - verifyNoNilFields(action.data, selectImageNoNilFields, 'image'); + if (!action.data.drive) { + verifyNoNilFields(action.data, selectImageNoNilFields, 'image'); + } if (!_.isString(action.data.path)) { throw errors.createError({ @@ -456,7 +458,7 @@ function storeReducer( !constraints.isDriveSizeRecommended(drive, action.data) ) { return storeReducer(accState, { - type: Actions.DESELECT_DRIVE, + type: Actions.DESELECT_TARGET, data: device, }); } @@ -467,7 +469,7 @@ function storeReducer( ).setIn(['selection', 'image'], Immutable.fromJS(action.data)); } - case Actions.DESELECT_DRIVE: { + case Actions.DESELECT_TARGET: { // Type: action.data : String if (!action.data) { @@ -491,7 +493,7 @@ function storeReducer( ); } - case Actions.DESELECT_IMAGE: { + case Actions.DESELECT_SOURCE: { return state.deleteIn(['selection', 'image']); } diff --git a/lib/gui/app/modules/image-writer.ts b/lib/gui/app/modules/image-writer.ts index 76c70fcd..e1ff0670 100644 --- a/lib/gui/app/modules/image-writer.ts +++ b/lib/gui/app/modules/image-writer.ts @@ -25,7 +25,7 @@ import * as path from 'path'; import * as packageJSON from '../../../../package.json'; import * as errors from '../../../shared/errors'; import * as permissions from '../../../shared/permissions'; -import { SourceOptions } from '../components/source-selector/source-selector'; +import { SourceMetadata } from '../components/source-selector/source-selector'; import * as flashState from '../models/flash-state'; import * as selectionState from '../models/selection-state'; import * as settings from '../models/settings'; @@ -134,15 +134,11 @@ interface FlashResults { cancelled?: boolean; } -/** - * @summary Perform write operation - */ -async function performWrite( - image: string, +export async function performWrite( + image: SourceMetadata, drives: DrivelistDrive[], onProgress: sdk.multiWrite.OnProgressFunction, - source: SourceOptions, -): Promise { +): Promise<{ cancelled?: boolean }> { let cancelled = false; ipc.serve(); const { @@ -196,10 +192,9 @@ async function performWrite( ipc.server.on('ready', (_data, socket) => { ipc.server.emit(socket, 'write', { - imagePath: image, + image, destinations: drives, - source, - SourceType: source.SourceType.name, + SourceType: image.SourceType.name, validateWriteOnSuccess, autoBlockmapping, unmountOnSuccess, @@ -258,9 +253,8 @@ async function performWrite( * @summary Flash an image to drives */ export async function flash( - image: string, + image: SourceMetadata, drives: DrivelistDrive[], - source: SourceOptions, // This function is a parameter so it can be mocked in tests write = performWrite, ): Promise { @@ -287,12 +281,7 @@ export async function flash( analytics.logEvent('Flash', analyticsData); try { - const result = await write( - image, - drives, - flashState.setProgressState, - source, - ); + const result = await write(image, drives, flashState.setProgressState); flashState.unsetFlashingFlag(result); } catch (error) { flashState.unsetFlashingFlag({ cancelled: false, errorCode: error.code }); diff --git a/lib/gui/app/pages/main/Flash.tsx b/lib/gui/app/pages/main/Flash.tsx index b61853d4..58ea0895 100644 --- a/lib/gui/app/pages/main/Flash.tsx +++ b/lib/gui/app/pages/main/Flash.tsx @@ -23,7 +23,6 @@ import { Flex, Modal, Txt } from 'rendition'; import * as constraints from '../../../../shared/drive-constraints'; import * as messages from '../../../../shared/messages'; import { ProgressButton } from '../../components/progress-button/progress-button'; -import { SourceOptions } from '../../components/source-selector/source-selector'; import * as availableDrives from '../../models/available-drives'; import * as flashState from '../../models/flash-state'; import * as selection from '../../models/selection-state'; @@ -79,7 +78,6 @@ const getErrorMessageFromCode = (errorCode: string) => { async function flashImageToDrive( isFlashing: boolean, goToSuccess: () => void, - sourceOptions: SourceOptions, ): Promise { const devices = selection.getSelectedDevices(); const image: any = selection.getImage(); @@ -98,7 +96,7 @@ async function flashImageToDrive( const iconPath = path.join('media', 'icon.png'); const basename = path.basename(image.path); try { - await imageWriter.flash(image.path, drives, sourceOptions); + await imageWriter.flash(image, drives); if (!flashState.wasLastFlashCancelled()) { const flashResults: any = flashState.getFlashResults(); notification.send( @@ -146,7 +144,6 @@ const formatSeconds = (totalSeconds: number) => { interface FlashStepProps { shouldFlashStepBeDisabled: boolean; goToSuccess: () => void; - source: SourceOptions; isFlashing: boolean; style?: React.CSSProperties; // TODO: factorize @@ -187,7 +184,6 @@ export class FlashStep extends React.PureComponent< errorMessage: await flashImageToDrive( this.props.isFlashing, this.props.goToSuccess, - this.props.source, ), }); } @@ -230,7 +226,6 @@ export class FlashStep extends React.PureComponent< errorMessage: await flashImageToDrive( this.props.isFlashing, this.props.goToSuccess, - this.props.source, ), }); } diff --git a/lib/gui/app/pages/main/MainPage.tsx b/lib/gui/app/pages/main/MainPage.tsx index e2306540..aca2b53b 100644 --- a/lib/gui/app/pages/main/MainPage.tsx +++ b/lib/gui/app/pages/main/MainPage.tsx @@ -17,7 +17,6 @@ import CogSvg from '@fortawesome/fontawesome-free/svgs/solid/cog.svg'; import QuestionCircleSvg from '@fortawesome/fontawesome-free/svgs/solid/question-circle.svg'; -import { sourceDestination } from 'etcher-sdk'; import * as _ from 'lodash'; import * as path from 'path'; import * as React from 'react'; @@ -28,10 +27,7 @@ import FinishPage from '../../components/finish/finish'; import { ReducedFlashingInfos } from '../../components/reduced-flashing-infos/reduced-flashing-infos'; import { SafeWebview } from '../../components/safe-webview/safe-webview'; import { SettingsModal } from '../../components/settings/settings'; -import { - SourceOptions, - SourceSelector, -} from '../../components/source-selector/source-selector'; +import { SourceSelector } from '../../components/source-selector/source-selector'; import * as flashState from '../../models/flash-state'; import * as selectionState from '../../models/selection-state'; import * as settings from '../../models/settings'; @@ -75,9 +71,12 @@ function getImageBasename() { return ''; } - const selectionImageName = selectionState.getImageName(); - const imageBasename = path.basename(selectionState.getImagePath()); - return selectionImageName || imageBasename; + const image = selectionState.getImage(); + if (image.drive) { + return image.drive.description; + } + const imageBasename = path.basename(image.path); + return image.name || imageBasename; } const StepBorder = styled.div<{ @@ -115,7 +114,6 @@ interface MainPageState { current: 'main' | 'success'; isWebviewShowing: boolean; hideSettings: boolean; - source: SourceOptions; featuredProjectURL?: string; } @@ -129,10 +127,6 @@ export class MainPage extends React.Component< current: 'main', isWebviewShowing: false, hideSettings: true, - source: { - imagePath: '', - SourceType: sourceDestination.File, - }, ...this.stateHelper(), }; } @@ -246,12 +240,7 @@ export class MainPage extends React.Component< > {notFlashingOrSplitView && ( <> - - this.setState({ source }) - } - /> + @@ -316,7 +305,6 @@ export class MainPage extends React.Component< this.setState({ current: 'success' })} shouldFlashStepBeDisabled={shouldFlashStepBeDisabled} - source={this.state.source} isFlashing={this.state.isFlashing} step={state.type} percentage={state.percentage} diff --git a/lib/gui/modules/child-writer.ts b/lib/gui/modules/child-writer.ts index 24052220..61fafe72 100644 --- a/lib/gui/modules/child-writer.ts +++ b/lib/gui/modules/child-writer.ts @@ -20,10 +20,11 @@ import { cleanupTmpFiles } from 'etcher-sdk/build/tmp'; import * as ipc from 'node-ipc'; import { totalmem } from 'os'; +import { BlockDevice, File, Http } from 'etcher-sdk/build/source-destination'; import { toJSON } from '../../shared/errors'; import { GENERAL_ERROR, SUCCESS } from '../../shared/exit-codes'; import { delay } from '../../shared/utils'; -import { SourceOptions } from '../app/components/source-selector/source-selector'; +import { SourceMetadata } from '../app/components/source-selector/source-selector'; ipc.config.id = process.env.IPC_CLIENT_ID as string; ipc.config.socketRoot = process.env.IPC_SOCKET_ROOT as string; @@ -143,13 +144,12 @@ async function writeAndValidate({ } interface WriteOptions { - imagePath: string; + image: SourceMetadata; destinations: DrivelistDrive[]; unmountOnSuccess: boolean; validateWriteOnSuccess: boolean; autoBlockmapping: boolean; decompressFirst: boolean; - source: SourceOptions; SourceType: string; } @@ -228,7 +228,7 @@ ipc.connectTo(IPC_SERVER_ID, () => { }; const destinations = options.destinations.map((d) => d.device); - log(`Image: ${options.imagePath}`); + const imagePath = options.image.path; log(`Devices: ${destinations.join(', ')}`); log(`Umount on success: ${options.unmountOnSuccess}`); log(`Validate on success: ${options.validateWriteOnSuccess}`); @@ -243,18 +243,23 @@ ipc.connectTo(IPC_SERVER_ID, () => { }); }); const { SourceType } = options; - let source; - if (SourceType === sdk.sourceDestination.File.name) { - source = new sdk.sourceDestination.File({ - path: options.imagePath, - }); - } else { - source = new sdk.sourceDestination.Http({ - url: options.imagePath, - avoidRandomAccess: true, - }); - } try { + let source; + if (options.image.drive) { + source = new BlockDevice({ + drive: options.image.drive, + write: false, + direct: !options.autoBlockmapping, + }); + } else { + if (SourceType === File.name) { + source = new File({ + path: imagePath, + }); + } else { + source = new Http({ url: imagePath, avoidRandomAccess: true }); + } + } const results = await writeAndValidate({ source, destinations: dests, diff --git a/lib/shared/drive-constraints.ts b/lib/shared/drive-constraints.ts index 8b56ad87..f8630de8 100644 --- a/lib/shared/drive-constraints.ts +++ b/lib/shared/drive-constraints.ts @@ -20,6 +20,7 @@ import * as pathIsInside from 'path-is-inside'; import * as prettyBytes from 'pretty-bytes'; import * as messages from './messages'; +import { SourceMetadata } from '../gui/app/components/source-selector/source-selector'; /** * @summary The default unknown size for things such as images and drives @@ -44,13 +45,22 @@ export function isSystemDrive(drive: DrivelistDrive): boolean { } export interface Image { - path?: string; + path: string; isSizeEstimated?: boolean; compressedSize?: number; recommendedDriveSize?: number; size?: number; } +function sourceIsInsideDrive(source: string, drive: DrivelistDrive) { + for (const mountpoint of drive.mountpoints || []) { + if (pathIsInside(source, mountpoint.path)) { + return true; + } + } + return false; +} + /** * @summary Check if a drive is source drive * @@ -60,11 +70,16 @@ export interface Image { */ export function isSourceDrive( drive: DrivelistDrive, - image: Image = {}, + selection?: SourceMetadata, ): boolean { - for (const mountpoint of drive.mountpoints || []) { - if (image.path !== undefined && pathIsInside(image.path, mountpoint.path)) { - return true; + if (selection) { + if (selection.drive) { + const sourcePath = selection.drive.devicePath || selection.drive.device; + const drivePath = drive.devicePath || drive.device; + return pathIsInside(sourcePath, drivePath); + } + if (selection.path) { + return sourceIsInsideDrive(selection.path, drive); } } return false; @@ -112,7 +127,7 @@ export function isDriveValid(drive: DrivelistDrive, image: Image): boolean { return ( !isDriveLocked(drive) && isDriveLargeEnough(drive, image) && - !isSourceDrive(drive, image) && + !isSourceDrive(drive, image as SourceMetadata) && !isDriveDisabled(drive) ); } @@ -167,7 +182,7 @@ export const COMPATIBILITY_STATUS_TYPES = { */ export function getDriveImageCompatibilityStatuses( drive: DrivelistDrive, - image: Image = {}, + image: Image, ) { const statusList = []; @@ -191,7 +206,7 @@ export function getDriveImageCompatibilityStatuses( message: messages.compatibility.tooSmall(prettyBytes(relativeBytes)), }); } else { - if (isSourceDrive(drive, image)) { + if (isSourceDrive(drive, image as SourceMetadata)) { statusList.push({ type: COMPATIBILITY_STATUS_TYPES.ERROR, message: messages.compatibility.containsImage(), diff --git a/lib/shared/messages.ts b/lib/shared/messages.ts index d88c1ff3..500c3468 100644 --- a/lib/shared/messages.ts +++ b/lib/shared/messages.ts @@ -143,9 +143,9 @@ export const error = { ].join(' '); }, - openImage: (imageBasename: string, errorMessage: string) => { + openSource: (sourceName: string, errorMessage: string) => { return [ - `Something went wrong while opening ${imageBasename}\n\n`, + `Something went wrong while opening ${sourceName}\n\n`, `Error: ${errorMessage}`, ].join(''); }, diff --git a/tests/gui/models/available-drives.spec.ts b/tests/gui/models/available-drives.spec.ts index a28fc493..126a4640 100644 --- a/tests/gui/models/available-drives.spec.ts +++ b/tests/gui/models/available-drives.spec.ts @@ -157,7 +157,7 @@ describe('Model: availableDrives', function () { } selectionState.clear(); - selectionState.selectImage({ + selectionState.selectSource({ path: this.imagePath, extension: 'img', size: 999999999, diff --git a/tests/gui/models/selection-state.spec.ts b/tests/gui/models/selection-state.spec.ts index 6a690ed9..234dde8b 100644 --- a/tests/gui/models/selection-state.spec.ts +++ b/tests/gui/models/selection-state.spec.ts @@ -359,7 +359,7 @@ describe('Model: selectionState', function () { logo: 'Raspbian', }; - selectionState.selectImage(this.image); + selectionState.selectSource(this.image); }); describe('.selectDrive()', function () { @@ -445,7 +445,7 @@ describe('Model: selectionState', function () { describe('.selectImage()', function () { it('should override the image', function () { - selectionState.selectImage({ + selectionState.selectSource({ path: 'bar.img', extension: 'img', size: 999999999, @@ -476,7 +476,7 @@ describe('Model: selectionState', function () { afterEach(selectionState.clear); it('should be able to set an image', function () { - selectionState.selectImage({ + selectionState.selectSource({ path: 'foo.img', extension: 'img', size: 999999999, @@ -490,7 +490,7 @@ describe('Model: selectionState', function () { }); it('should be able to set an image with an archive extension', function () { - selectionState.selectImage({ + selectionState.selectSource({ path: 'foo.zip', extension: 'img', archiveExtension: 'zip', @@ -503,7 +503,7 @@ describe('Model: selectionState', function () { }); it('should infer a compressed raw image if the penultimate extension is missing', function () { - selectionState.selectImage({ + selectionState.selectSource({ path: 'foo.xz', extension: 'img', archiveExtension: 'xz', @@ -516,7 +516,7 @@ describe('Model: selectionState', function () { }); it('should infer a compressed raw image if the penultimate extension is not a file extension', function () { - selectionState.selectImage({ + selectionState.selectSource({ path: 'something.linux-x86-64.gz', extension: 'img', archiveExtension: 'gz', @@ -530,7 +530,7 @@ describe('Model: selectionState', function () { it('should throw if no path', function () { expect(function () { - selectionState.selectImage({ + selectionState.selectSource({ extension: 'img', size: 999999999, isSizeEstimated: false, @@ -540,7 +540,7 @@ describe('Model: selectionState', function () { it('should throw if path is not a string', function () { expect(function () { - selectionState.selectImage({ + selectionState.selectSource({ path: 123, extension: 'img', size: 999999999, @@ -551,7 +551,7 @@ describe('Model: selectionState', function () { it('should throw if the original size is not a number', function () { expect(function () { - selectionState.selectImage({ + selectionState.selectSource({ path: 'foo.img', extension: 'img', size: 999999999, @@ -563,7 +563,7 @@ describe('Model: selectionState', function () { it('should throw if the original size is a float number', function () { expect(function () { - selectionState.selectImage({ + selectionState.selectSource({ path: 'foo.img', extension: 'img', size: 999999999, @@ -575,7 +575,7 @@ describe('Model: selectionState', function () { it('should throw if the original size is negative', function () { expect(function () { - selectionState.selectImage({ + selectionState.selectSource({ path: 'foo.img', extension: 'img', size: 999999999, @@ -587,7 +587,7 @@ describe('Model: selectionState', function () { it('should throw if the final size is not a number', function () { expect(function () { - selectionState.selectImage({ + selectionState.selectSource({ path: 'foo.img', extension: 'img', size: '999999999', @@ -598,7 +598,7 @@ describe('Model: selectionState', function () { it('should throw if the final size is a float number', function () { expect(function () { - selectionState.selectImage({ + selectionState.selectSource({ path: 'foo.img', extension: 'img', size: 999999999.999, @@ -609,7 +609,7 @@ describe('Model: selectionState', function () { it('should throw if the final size is negative', function () { expect(function () { - selectionState.selectImage({ + selectionState.selectSource({ path: 'foo.img', extension: 'img', size: -1, @@ -620,7 +620,7 @@ describe('Model: selectionState', function () { it("should throw if url is defined but it's not a string", function () { expect(function () { - selectionState.selectImage({ + selectionState.selectSource({ path: 'foo.img', extension: 'img', size: 999999999, @@ -632,7 +632,7 @@ describe('Model: selectionState', function () { it("should throw if name is defined but it's not a string", function () { expect(function () { - selectionState.selectImage({ + selectionState.selectSource({ path: 'foo.img', extension: 'img', size: 999999999, @@ -644,7 +644,7 @@ describe('Model: selectionState', function () { it("should throw if logo is defined but it's not a string", function () { expect(function () { - selectionState.selectImage({ + selectionState.selectSource({ path: 'foo.img', extension: 'img', size: 999999999, @@ -667,7 +667,7 @@ describe('Model: selectionState', function () { selectionState.selectDrive('/dev/disk1'); expect(selectionState.hasDrive()).to.be.true; - selectionState.selectImage({ + selectionState.selectSource({ path: 'foo.img', extension: 'img', size: 1234567890, @@ -691,7 +691,7 @@ describe('Model: selectionState', function () { selectionState.selectDrive('/dev/disk1'); expect(selectionState.hasDrive()).to.be.true; - selectionState.selectImage({ + selectionState.selectSource({ path: 'foo.img', extension: 'img', size: 999999999, @@ -726,7 +726,7 @@ describe('Model: selectionState', function () { selectionState.selectDrive('/dev/disk1'); expect(selectionState.hasDrive()).to.be.true; - selectionState.selectImage({ + selectionState.selectSource({ path: imagePath, extension: 'img', size: 999999999, @@ -752,7 +752,7 @@ describe('Model: selectionState', function () { selectionState.selectDrive('/dev/disk1'); - selectionState.selectImage({ + selectionState.selectSource({ path: 'foo.img', extension: 'img', size: 999999999, @@ -850,7 +850,7 @@ describe('Model: selectionState', function () { selectionState.selectDrive('/dev/disk2'); selectionState.selectDrive('/dev/disk3'); - selectionState.selectImage({ + selectionState.selectSource({ path: 'foo.img', extension: 'img', size: 999999999, diff --git a/tests/gui/modules/image-writer.spec.ts b/tests/gui/modules/image-writer.spec.ts index ab820cd7..677b2f6c 100644 --- a/tests/gui/modules/image-writer.spec.ts +++ b/tests/gui/modules/image-writer.spec.ts @@ -28,10 +28,12 @@ const fakeDrive: DrivelistDrive = {}; describe('Browser: imageWriter', () => { describe('.flash()', () => { - const imagePath = 'foo.img'; - const sourceOptions = { - imagePath, + const image = { + hasMBR: false, + partitions: [], + path: 'foo.img', SourceType: sourceDestination.File, + extension: 'img', }; describe('given a successful write', () => { @@ -58,12 +60,7 @@ describe('Browser: imageWriter', () => { }); try { - await imageWriter.flash( - imagePath, - [fakeDrive], - sourceOptions, - performWriteStub, - ); + imageWriter.flash(image, [fakeDrive], performWriteStub); } catch { // noop } finally { @@ -79,18 +76,8 @@ describe('Browser: imageWriter', () => { try { await Promise.all([ - imageWriter.flash( - imagePath, - [fakeDrive], - sourceOptions, - performWriteStub, - ), - imageWriter.flash( - imagePath, - [fakeDrive], - sourceOptions, - performWriteStub, - ), + imageWriter.flash(image, [fakeDrive], performWriteStub), + imageWriter.flash(image, [fakeDrive], performWriteStub), ]); assert.fail('Writing twice should fail'); } catch (error) { @@ -117,12 +104,7 @@ describe('Browser: imageWriter', () => { it('should set flashing to false when done', async () => { try { - await imageWriter.flash( - imagePath, - [fakeDrive], - sourceOptions, - performWriteStub, - ); + await imageWriter.flash(image, [fakeDrive], performWriteStub); } catch { // noop } finally { @@ -132,12 +114,7 @@ describe('Browser: imageWriter', () => { it('should set the error code in the flash results', async () => { try { - await imageWriter.flash( - imagePath, - [fakeDrive], - sourceOptions, - performWriteStub, - ); + await imageWriter.flash(image, [fakeDrive], performWriteStub); } catch { // noop } finally { @@ -152,12 +129,7 @@ describe('Browser: imageWriter', () => { sourceChecksum: '1234', }); try { - await imageWriter.flash( - imagePath, - [fakeDrive], - sourceOptions, - performWriteStub, - ); + await imageWriter.flash(image, [fakeDrive], performWriteStub); } catch (error) { expect(error).to.be.an.instanceof(Error); expect(error.message).to.equal('write error'); diff --git a/tests/shared/drive-constraints.spec.ts b/tests/shared/drive-constraints.spec.ts index e5ecf1de..62687fde 100644 --- a/tests/shared/drive-constraints.spec.ts +++ b/tests/shared/drive-constraints.spec.ts @@ -16,6 +16,7 @@ import { expect } from 'chai'; import { Drive as DrivelistDrive } from 'drivelist'; +import { sourceDestination } from 'etcher-sdk'; import * as _ from 'lodash'; import * as path from 'path'; @@ -126,6 +127,9 @@ describe('Shared: DriveConstraints', function () { } as DrivelistDrive, { path: '/Volumes/Untitled/image.img', + hasMBR: false, + partitions: [], + SourceType: sourceDestination.File, }, ); @@ -160,6 +164,9 @@ describe('Shared: DriveConstraints', function () { } as DrivelistDrive, { path: 'E:\\image.img', + hasMBR: false, + partitions: [], + SourceType: sourceDestination.File, }, ); @@ -182,6 +189,9 @@ describe('Shared: DriveConstraints', function () { } as DrivelistDrive, { path: 'E:\\foo\\bar\\image.img', + hasMBR: false, + partitions: [], + SourceType: sourceDestination.File, }, ); @@ -204,6 +214,9 @@ describe('Shared: DriveConstraints', function () { } as DrivelistDrive, { path: 'G:\\image.img', + hasMBR: false, + partitions: [], + SourceType: sourceDestination.File, }, ); @@ -222,6 +235,9 @@ describe('Shared: DriveConstraints', function () { } as DrivelistDrive, { path: 'E:\\foo/image.img', + hasMBR: false, + partitions: [], + SourceType: sourceDestination.File, }, ); @@ -252,6 +268,9 @@ describe('Shared: DriveConstraints', function () { } as DrivelistDrive, { path: '/image.img', + hasMBR: false, + partitions: [], + SourceType: sourceDestination.File, }, ); @@ -272,6 +291,9 @@ describe('Shared: DriveConstraints', function () { } as DrivelistDrive, { path: '/Volumes/A/image.img', + hasMBR: false, + partitions: [], + SourceType: sourceDestination.File, }, ); @@ -292,6 +314,9 @@ describe('Shared: DriveConstraints', function () { } as DrivelistDrive, { path: '/Volumes/A/foo/bar/image.img', + hasMBR: false, + partitions: [], + SourceType: sourceDestination.File, }, ); @@ -312,6 +337,9 @@ describe('Shared: DriveConstraints', function () { } as DrivelistDrive, { path: '/Volumes/C/image.img', + hasMBR: false, + partitions: [], + SourceType: sourceDestination.File, }, ); @@ -329,6 +357,9 @@ describe('Shared: DriveConstraints', function () { } as DrivelistDrive, { path: '/Volumes/foo/image.img', + hasMBR: false, + partitions: [], + SourceType: sourceDestination.File, }, ); From bb04098062f84462200468159510cc4b77cb9ea5 Mon Sep 17 00:00:00 2001 From: Lorenzo Alberto Maria Ambrosi Date: Fri, 10 Jul 2020 18:21:55 +0200 Subject: [PATCH 03/12] Reword macOS Catalina askpass message Change-type: patch Changelog-entry: Reword macOS Catalina askpass message Signed-off-by: Lorenzo Alberto Maria Ambrosi --- lib/shared/catalina-sudo/sudo-askpass.osascript.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/shared/catalina-sudo/sudo-askpass.osascript.js b/lib/shared/catalina-sudo/sudo-askpass.osascript.js index 854d1d3a..32ad4025 100755 --- a/lib/shared/catalina-sudo/sudo-askpass.osascript.js +++ b/lib/shared/catalina-sudo/sudo-askpass.osascript.js @@ -5,9 +5,9 @@ ObjC.import('stdlib') const app = Application.currentApplication() app.includeStandardAdditions = true -const result = app.displayDialog('balenaEtcher wants to make changes. Type your password to allow this.', { +const result = app.displayDialog('balenaEtcher needs privileged access in order to flash disks.\n\nType your password to allow this.', { defaultAnswer: '', - withIcon: 'stop', + withIcon: 'caution', buttons: ['Cancel', 'Ok'], defaultButton: 'Ok', hiddenAnswer: true, From aa72c5d3bb051f552ab3cfd0a67681dcc5407e53 Mon Sep 17 00:00:00 2001 From: Lorenzo Alberto Maria Ambrosi Date: Tue, 25 Aug 2020 10:03:00 +0200 Subject: [PATCH 04/12] Ignore vscode workspace folder Change-type: patch Signed-off-by: Lorenzo Alberto Maria Ambrosi --- .gitignore | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.gitignore b/.gitignore index c9602d02..fcabc3d6 100644 --- a/.gitignore +++ b/.gitignore @@ -47,3 +47,7 @@ node_modules # OSX files .DS_Store + +# VSCode files + +.vscode From 42838eba095220ecb254aadc314df5d88822d170 Mon Sep 17 00:00:00 2001 From: Lorenzo Alberto Maria Ambrosi Date: Thu, 27 Aug 2020 10:26:21 +0200 Subject: [PATCH 05/12] Override cached window's zoomFactor Change-type: patch Signed-off-by: Lorenzo Alberto Maria Ambrosi --- lib/gui/etcher.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/lib/gui/etcher.ts b/lib/gui/etcher.ts index 044e9f13..59163bad 100644 --- a/lib/gui/etcher.ts +++ b/lib/gui/etcher.ts @@ -161,6 +161,9 @@ async function createMainWindow() { // Prevent flash of white when starting the application mainWindow.on('ready-to-show', () => { console.timeEnd('ready-to-show'); + // Electron sometimes caches the zoomFactor + // making it obnoxious to switch back-and-forth + mainWindow.webContents.setZoomFactor(width / defaultWidth); mainWindow.show(); }); From 093008dee7a936c91b9ecdde8bebee9e6dace5b5 Mon Sep 17 00:00:00 2001 From: Lorenzo Alberto Maria Ambrosi Date: Thu, 23 Jul 2020 14:50:28 +0200 Subject: [PATCH 06/12] Rework system & large drives handling logic Change-type: patch Changelog-entry: Rework system & large drives handling logic Signed-off-by: Lorenzo Alberto Maria Ambrosi --- .../drive-selector/drive-selector.tsx | 227 +++++--- .../drive-status-warning-modal.tsx | 82 +++ .../source-selector/source-selector.tsx | 181 ++++--- .../target-selector-button.tsx | 72 +-- .../target-selector/target-selector.tsx | 33 +- lib/gui/app/css/main.css | 10 +- lib/gui/app/models/available-drives.ts | 4 +- lib/gui/app/models/leds.ts | 6 +- lib/gui/app/models/selection-state.ts | 5 +- lib/gui/app/modules/image-writer.ts | 2 +- lib/gui/app/modules/progress-status.ts | 2 +- lib/gui/app/pages/main/Flash.tsx | 121 ++--- lib/gui/app/pages/main/MainPage.tsx | 17 +- lib/gui/app/styled-components.tsx | 83 ++- lib/gui/app/theme.ts | 23 +- lib/gui/modules/child-writer.ts | 2 +- lib/shared/drive-constraints.ts | 163 +++--- lib/shared/messages.ts | 26 +- lib/shared/units.ts | 7 +- tests/gui/modules/image-writer.spec.ts | 7 +- tests/shared/drive-constraints.spec.ts | 490 ++++++------------ 21 files changed, 826 insertions(+), 737 deletions(-) create mode 100644 lib/gui/app/components/drive-status-warning-modal/drive-status-warning-modal.tsx diff --git a/lib/gui/app/components/drive-selector/drive-selector.tsx b/lib/gui/app/components/drive-selector/drive-selector.tsx index cdcb374f..290db14c 100644 --- a/lib/gui/app/components/drive-selector/drive-selector.tsx +++ b/lib/gui/app/components/drive-selector/drive-selector.tsx @@ -16,7 +16,7 @@ import ExclamationTriangleSvg from '@fortawesome/fontawesome-free/svgs/solid/exclamation-triangle.svg'; import ChevronDownSvg from '@fortawesome/fontawesome-free/svgs/solid/chevron-down.svg'; -import { scanner, sourceDestination } from 'etcher-sdk'; +import * as sourceDestination from 'etcher-sdk/build/source-destination/'; import * as React from 'react'; import { Flex, @@ -31,25 +31,22 @@ import styled from 'styled-components'; import { getDriveImageCompatibilityStatuses, - hasListDriveImageCompatibilityStatus, isDriveValid, DriveStatus, - Image, + DrivelistDrive, + isDriveSizeLarge, } from '../../../../shared/drive-constraints'; -import { compatibility } from '../../../../shared/messages'; -import { bytesToClosestUnit } from '../../../../shared/units'; +import { compatibility, warning } from '../../../../shared/messages'; +import * as prettyBytes from 'pretty-bytes'; import { getDrives, hasAvailableDrives } from '../../models/available-drives'; -import { - getImage, - getSelectedDrives, - isDriveSelected, -} from '../../models/selection-state'; +import { getImage, isDriveSelected } from '../../models/selection-state'; import { store } from '../../models/store'; import { logEvent, logException } from '../../modules/analytics'; import { open as openExternal } from '../../os/open-external/services/open-external'; -import { Modal, ScrollableFlex } from '../../styled-components'; +import { Alert, Modal, ScrollableFlex } from '../../styled-components'; import DriveSVGIcon from '../../../assets/tgt.svg'; +import { SourceMetadata } from '../source-selector/source-selector'; interface UsbbootDrive extends sourceDestination.UsbbootDrive { progress: number; @@ -64,7 +61,7 @@ interface DriverlessDrive { linkCTA: string; } -type Drive = scanner.adapters.DrivelistDrive | DriverlessDrive | UsbbootDrive; +type Drive = DrivelistDrive | DriverlessDrive | UsbbootDrive; function isUsbbootDrive(drive: Drive): drive is UsbbootDrive { return (drive as UsbbootDrive).progress !== undefined; @@ -74,37 +71,78 @@ function isDriverlessDrive(drive: Drive): drive is DriverlessDrive { return (drive as DriverlessDrive).link !== undefined; } -function isDrivelistDrive( - drive: Drive, -): drive is scanner.adapters.DrivelistDrive { - return typeof (drive as scanner.adapters.DrivelistDrive).size === 'number'; +function isDrivelistDrive(drive: Drive): drive is DrivelistDrive { + return typeof (drive as DrivelistDrive).size === 'number'; } -const DrivesTable = styled(({ refFn, ...props }) => { - return ( -
- ref={refFn} {...props} /> -
- ); -})` - [data-display='table-head'] [data-display='table-cell'] { +const DrivesTable = styled(({ refFn, ...props }) => ( +
+ ref={refFn} {...props} /> +
+))` + [data-display='table-head'] + > [data-display='table-row'] + > [data-display='table-cell'] { position: sticky; top: 0; background-color: ${(props) => props.theme.colors.quartenary.light}; + + input[type='checkbox'] + div { + display: ${({ multipleSelection }) => + multipleSelection ? 'flex' : 'none'}; + } + + &:first-child { + padding-left: 15px; + } + + &:nth-child(2) { + width: 38%; + } + + &:nth-child(3) { + width: 15%; + } + + &:nth-child(4) { + width: 15%; + } + + &:nth-child(5) { + width: 32%; + } } - [data-display='table-cell']:first-child { - padding-left: 15px; - } + [data-display='table-body'] > [data-display='table-row'] { + > [data-display='table-cell']:first-child { + padding-left: 15px; + } - [data-display='table-cell']:last-child { - width: 150px; + > [data-display='table-cell']:last-child { + padding-right: 0; + } + + &[data-highlight='true'] { + &.system { + background-color: ${(props) => + props.showWarnings ? '#fff5e6' : '#e8f5fc'}; + } + + > [data-display='table-cell']:first-child { + box-shadow: none; + } + } } && [data-display='table-row'] > [data-display='table-cell'] { padding: 6px 8px; color: #2a506f; } + + input[type='checkbox'] + div { + border-radius: ${({ multipleSelection }) => + multipleSelection ? '4px' : '50%'}; + } `; function badgeShadeFromStatus(status: string) { @@ -112,6 +150,7 @@ function badgeShadeFromStatus(status: string) { case compatibility.containsImage(): return 16; case compatibility.system(): + case compatibility.tooSmall(): return 5; default: return 14; @@ -147,39 +186,40 @@ const InitProgress = styled( export interface DriveSelectorProps extends Omit { - multipleSelection?: boolean; + multipleSelection: boolean; + showWarnings?: boolean; cancel: () => void; - done: (drives: scanner.adapters.DrivelistDrive[]) => void; + done: (drives: DrivelistDrive[]) => void; titleLabel: string; emptyListLabel: string; + selectedList?: DrivelistDrive[]; + updateSelectedList?: () => DrivelistDrive[]; } interface DriveSelectorState { drives: Drive[]; - image: Image; + image?: SourceMetadata; missingDriversModal: { drive?: DriverlessDrive }; - selectedList: scanner.adapters.DrivelistDrive[]; + selectedList: DrivelistDrive[]; showSystemDrives: boolean; } +function isSystemDrive(drive: Drive) { + return isDrivelistDrive(drive) && drive.isSystem; +} + export class DriveSelector extends React.Component< DriveSelectorProps, DriveSelectorState > { private unsubscribe: (() => void) | undefined; - multipleSelection: boolean = true; tableColumns: Array>; constructor(props: DriveSelectorProps) { super(props); const defaultMissingDriversModalState: { drive?: DriverlessDrive } = {}; - const selectedList = getSelectedDrives(); - const multipleSelection = this.props.multipleSelection; - this.multipleSelection = - multipleSelection !== undefined - ? !!multipleSelection - : this.multipleSelection; + const selectedList = this.props.selectedList || []; this.state = { drives: getDrives(), @@ -194,14 +234,23 @@ export class DriveSelector extends React.Component< field: 'description', label: 'Name', render: (description: string, drive: Drive) => { - return isDrivelistDrive(drive) && drive.isSystem ? ( - - - {description} - - ) : ( - {description} - ); + if (isDrivelistDrive(drive)) { + const isLargeDrive = isDriveSizeLarge(drive); + const hasWarnings = + this.props.showWarnings && (isLargeDrive || drive.isSystem); + return ( + + {hasWarnings && ( + + )} + {description} + + ); + } + return {description}; }, }, { @@ -210,7 +259,7 @@ export class DriveSelector extends React.Component< label: 'Size', render: (_description: string, drive: Drive) => { if (isDrivelistDrive(drive) && drive.size !== null) { - return bytesToClosestUnit(drive.size); + return prettyBytes(drive.size); } }, }, @@ -241,21 +290,19 @@ export class DriveSelector extends React.Component< field: 'description', key: 'extra', // Space as empty string would use the field name as label - label: ' ', + label: , render: (_description: string, drive: Drive) => { if (isUsbbootDrive(drive)) { return this.renderProgress(drive.progress); } else if (isDrivelistDrive(drive)) { - return this.renderStatuses( - getDriveImageCompatibilityStatuses(drive, this.state.image), - ); + return this.renderStatuses(drive); } }, }, ]; } - private driveShouldBeDisabled(drive: Drive, image: any) { + private driveShouldBeDisabled(drive: Drive, image?: SourceMetadata) { return ( isUsbbootDrive(drive) || isDriverlessDrive(drive) || @@ -275,7 +322,7 @@ export class DriveSelector extends React.Component< }); } - private getDisabledDrives(drives: Drive[], image: any): string[] { + private getDisabledDrives(drives: Drive[], image?: SourceMetadata): string[] { return drives .filter((drive) => this.driveShouldBeDisabled(drive, image)) .map((drive) => drive.displayName); @@ -290,14 +337,45 @@ export class DriveSelector extends React.Component< ); } - private renderStatuses(statuses: DriveStatus[]) { + private warningFromStatus( + status: string, + drive: { device: string; size: number }, + ) { + switch (status) { + case compatibility.containsImage(): + return warning.sourceDrive(); + case compatibility.largeDrive(): + return warning.largeDriveSize(); + case compatibility.system(): + return warning.systemDrive(); + case compatibility.tooSmall(): + const recommendedDriveSize = + this.state.image?.recommendedDriveSize || this.state.image?.size || 0; + return warning.unrecommendedDriveSize({ recommendedDriveSize }, drive); + } + } + + private renderStatuses(drive: DrivelistDrive) { + const statuses: DriveStatus[] = getDriveImageCompatibilityStatuses( + drive, + this.state.image, + ).slice(0, 2); return ( // the column render fn expects a single Element <> {statuses.map((status) => { const badgeShade = badgeShadeFromStatus(status.message); + const warningMessage = this.warningFromStatus(status.message, { + device: drive.device, + size: drive.size || 0, + }); return ( - + {status.message} ); @@ -322,7 +400,9 @@ export class DriveSelector extends React.Component< this.setState({ drives, image, - selectedList: getSelectedDrives(), + selectedList: + (this.props.updateSelectedList && this.props.updateSelectedList()) || + [], }); }); } @@ -337,15 +417,13 @@ export class DriveSelector extends React.Component< const displayedDrives = this.getDisplayedDrives(drives); const disabledDrives = this.getDisabledDrives(drives, image); - const numberOfSystemDrives = drives.filter( - (drive) => isDrivelistDrive(drive) && drive.isSystem, - ).length; - const numberOfDisplayedSystemDrives = displayedDrives.filter( - (drive) => isDrivelistDrive(drive) && drive.isSystem, - ).length; + const numberOfSystemDrives = drives.filter(isSystemDrive).length; + const numberOfDisplayedSystemDrives = displayedDrives.filter(isSystemDrive) + .length; const numberOfHiddenSystemDrives = numberOfSystemDrives - numberOfDisplayedSystemDrives; - const hasStatus = hasListDriveImageCompatibilityStatus(selectedList, image); + const hasSystemDrives = selectedList.filter(isSystemDrive).length; + const showWarnings = this.props.showWarnings && hasSystemDrives; return ( done(selectedList)} action={`Select (${selectedList.length})`} primaryButtonProps={{ - primary: !hasStatus, - warning: hasStatus, + primary: !showWarnings, + warning: showWarnings, disabled: !hasAvailableDrives(), }} {...props} @@ -394,13 +472,17 @@ export class DriveSelector extends React.Component< t.setRowSelection(selectedList); } }} + multipleSelection={this.props.multipleSelection} columns={this.tableColumns} data={displayedDrives} disabledRows={disabledDrives} + getRowClass={(row: Drive) => + isDrivelistDrive(row) && row.isSystem ? ['system'] : [] + } rowKey="displayName" onCheck={(rows: Drive[]) => { const newSelection = rows.filter(isDrivelistDrive); - if (this.multipleSelection) { + if (this.props.multipleSelection) { this.setState({ selectedList: newSelection, }); @@ -417,7 +499,7 @@ export class DriveSelector extends React.Component< ) { return; } - if (this.multipleSelection) { + if (this.props.multipleSelection) { const newList = [...selectedList]; const selectedIndex = selectedList.findIndex( (drive) => drive.device === row.device, @@ -442,6 +524,7 @@ export class DriveSelector extends React.Component< this.setState({ showSystemDrives: true })} > @@ -452,6 +535,12 @@ export class DriveSelector extends React.Component< )}
)} + {this.props.showWarnings && hasSystemDrives ? ( + + Selecting your system drive is dangerous and will erase your + drive! + + ) : null} {missingDriversModal.drive !== undefined && ( diff --git a/lib/gui/app/components/drive-status-warning-modal/drive-status-warning-modal.tsx b/lib/gui/app/components/drive-status-warning-modal/drive-status-warning-modal.tsx new file mode 100644 index 00000000..e310c8da --- /dev/null +++ b/lib/gui/app/components/drive-status-warning-modal/drive-status-warning-modal.tsx @@ -0,0 +1,82 @@ +import ExclamationTriangleSvg from '@fortawesome/fontawesome-free/svgs/solid/exclamation-triangle.svg'; +import * as _ from 'lodash'; +import * as React from 'react'; +import { Badge, Flex, Txt, ModalProps } from 'rendition'; +import { Modal, ScrollableFlex } from '../../styled-components'; +import { middleEllipsis } from '../../utils/middle-ellipsis'; + +import { bytesToClosestUnit } from '../../../../shared/units'; +import { DriveWithWarnings } from '../../pages/main/Flash'; + +const DriveStatusWarningModal = ({ + done, + cancel, + isSystem, + drivesWithWarnings, +}: ModalProps & { + isSystem: boolean; + drivesWithWarnings: DriveWithWarnings[]; +}) => { + let warningSubtitle = 'You are about to erase an unusually large drive'; + let warningCta = 'Are you sure the selected drive is not a storage drive?'; + + if (isSystem) { + warningSubtitle = "You are about to erase your computer's drives"; + warningCta = 'Are you sure you want to flash your system drive?'; + } + return ( + + + + + + WARNING! + + + {warningSubtitle} + + {drivesWithWarnings.map((drive, i, array) => ( + <> + + {middleEllipsis(drive.description, 28)}{' '} + {bytesToClosestUnit(drive.size || 0)}{' '} + {drive.statuses[0].message} + + {i !== array.length - 1 ?
: null} + + ))} +
+ {warningCta} +
+
+ ); +}; + +export default DriveStatusWarningModal; diff --git a/lib/gui/app/components/source-selector/source-selector.tsx b/lib/gui/app/components/source-selector/source-selector.tsx index 69738224..c07fd83c 100644 --- a/lib/gui/app/components/source-selector/source-selector.tsx +++ b/lib/gui/app/components/source-selector/source-selector.tsx @@ -18,11 +18,12 @@ import CopySvg from '@fortawesome/fontawesome-free/svgs/solid/copy.svg'; import FileSvg from '@fortawesome/fontawesome-free/svgs/solid/file.svg'; import LinkSvg from '@fortawesome/fontawesome-free/svgs/solid/link.svg'; import ExclamationTriangleSvg from '@fortawesome/fontawesome-free/svgs/solid/exclamation-triangle.svg'; -import { sourceDestination, scanner } from 'etcher-sdk'; +import { sourceDestination } from 'etcher-sdk'; import { ipcRenderer, IpcRendererEvent } from 'electron'; import * as _ from 'lodash'; import { GPTPartition, MBRPartition } from 'partitioninfo'; import * as path from 'path'; +import * as prettyBytes from 'pretty-bytes'; import * as React from 'react'; import { Flex, @@ -38,7 +39,6 @@ import styled from 'styled-components'; import * as errors from '../../../../shared/errors'; import * as messages from '../../../../shared/messages'; import * as supportedFormats from '../../../../shared/supported-formats'; -import * as shared from '../../../../shared/units'; import * as selectionState from '../../models/selection-state'; import { observe } from '../../models/store'; import * as analytics from '../../modules/analytics'; @@ -59,6 +59,7 @@ import { SVGIcon } from '../svg-icon/svg-icon'; import ImageSvg from '../../../assets/image.svg'; import { DriveSelector } from '../drive-selector/drive-selector'; +import { DrivelistDrive } from '../../../../shared/drive-constraints'; const recentUrlImagesKey = 'recentUrlImages'; @@ -161,44 +162,46 @@ const URLSelector = ({ await done(imageURL); }} > - - - Use Image URL - - ) => - setImageURL(evt.target.value) - } - /> - - {recentImages.length > 0 && ( - - Recent - - ( - { - setImageURL(recent.href); - }} - style={{ - overflowWrap: 'break-word', - }} - > - {recent.pathname.split('/').pop()} - {recent.href} - - )) - .reverse()} - /> - + + + + Use Image URL + + ) => + setImageURL(evt.target.value) + } + /> - )} + {recentImages.length > 0 && ( + + Recent + + ( + { + setImageURL(recent.href); + }} + style={{ + overflowWrap: 'break-word', + }} + > + {recent.pathname.split('/').pop()} - {recent.href} + + )) + .reverse()} + /> + + + )} + ); }; @@ -243,11 +246,13 @@ export type Source = | typeof sourceDestination.Http; export interface SourceMetadata extends sourceDestination.Metadata { - hasMBR: boolean; - partitions: MBRPartition[] | GPTPartition[]; + hasMBR?: boolean; + partitions?: MBRPartition[] | GPTPartition[]; path: string; + displayName: string; + description: string; SourceType: Source; - drive?: scanner.adapters.DrivelistDrive; + drive?: DrivelistDrive; extension?: string; } @@ -326,7 +331,7 @@ export class SourceSelector extends React.Component< } private selectSource( - selected: string | scanner.adapters.DrivelistDrive, + selected: string | DrivelistDrive, SourceType: Source, ): { promise: Promise; cancel: () => void } { let cancelled = false; @@ -336,40 +341,43 @@ export class SourceSelector extends React.Component< }, promise: (async () => { const sourcePath = isString(selected) ? selected : selected.device; + let source; let metadata: SourceMetadata | undefined; if (isString(selected)) { - const source = await this.createSource(selected, SourceType); + if (SourceType === sourceDestination.Http && !isURL(selected)) { + this.handleError( + 'Unsupported protocol', + selected, + messages.error.unsupportedProtocol(), + ); + return; + } + + if (supportedFormats.looksLikeWindowsImage(selected)) { + analytics.logEvent('Possibly Windows image', { image: selected }); + this.setState({ + warning: { + message: messages.warning.looksLikeWindowsImage(), + title: 'Possible Windows image detected', + }, + }); + } + source = await this.createSource(selected, SourceType); + if (cancelled) { return; } + try { const innerSource = await source.getInnerSource(); if (cancelled) { return; } - metadata = await this.getMetadata(innerSource); + metadata = await this.getMetadata(innerSource, selected); if (cancelled) { return; } - if (SourceType === sourceDestination.Http && !isURL(selected)) { - this.handleError( - 'Unsupported protocol', - selected, - messages.error.unsupportedProtocol(), - ); - return; - } - if (supportedFormats.looksLikeWindowsImage(selected)) { - analytics.logEvent('Possibly Windows image', { image: selected }); - this.setState({ - warning: { - message: messages.warning.looksLikeWindowsImage(), - title: 'Possible Windows image detected', - }, - }); - } - metadata.extension = path.extname(selected).slice(1); - metadata.path = selected; + metadata.SourceType = SourceType; if (!metadata.hasMBR) { analytics.logEvent('Missing partition table', { metadata }); @@ -397,9 +405,9 @@ export class SourceSelector extends React.Component< } else { metadata = { path: selected.device, + displayName: selected.displayName, + description: selected.displayName, size: selected.size as SourceMetadata['size'], - hasMBR: false, - partitions: [], SourceType: sourceDestination.BlockDevice, drive: selected, }; @@ -425,7 +433,7 @@ export class SourceSelector extends React.Component< title: string, sourcePath: string, description: string, - error?: any, + error?: Error, ) { const imageError = errors.createUserError({ title, @@ -440,7 +448,8 @@ export class SourceSelector extends React.Component< } private async getMetadata( - source: sourceDestination.SourceDestination | sourceDestination.BlockDevice, + source: sourceDestination.SourceDestination, + selected: string | DrivelistDrive, ) { const metadata = (await source.getMetadata()) as SourceMetadata; const partitionTable = await source.getPartitionTable(); @@ -450,6 +459,10 @@ export class SourceSelector extends React.Component< } else { metadata.hasMBR = false; } + if (isString(selected)) { + metadata.extension = path.extname(selected).slice(1); + metadata.path = selected; + } return metadata; } @@ -517,20 +530,20 @@ export class SourceSelector extends React.Component< public render() { const { flashing } = this.props; const { showImageDetails, showURLSelector, showDriveSelector } = this.state; + const selectionImage = selectionState.getImage(); + let image: SourceMetadata | DrivelistDrive = + selectionImage !== undefined ? selectionImage : ({} as SourceMetadata); - const hasSource = selectionState.hasImage(); - let image = hasSource ? selectionState.getImage() : {}; - - image = image.drive ? image.drive : image; + image = image.drive ?? image; let cancelURLSelection = () => { // noop }; image.name = image.description || image.name; - const imagePath = image.path || ''; - const imageBasename = path.basename(image.path || ''); + const imagePath = image.path || image.displayName || ''; + const imageBasename = path.basename(imagePath); const imageName = image.name || ''; - const imageSize = image.size || ''; + const imageSize = image.size || 0; const imageLogo = image.logo || ''; return ( @@ -554,7 +567,7 @@ export class SourceSelector extends React.Component< }} /> - {hasSource ? ( + {selectionImage !== undefined ? ( <> )} - {shared.bytesToClosestUnit(imageSize)} + {prettyBytes(imageSize)} ) : ( <> @@ -684,15 +697,13 @@ export class SourceSelector extends React.Component< showDriveSelector: false, }); }} - done={async (drives: scanner.adapters.DrivelistDrive[]) => { - if (!drives.length) { - analytics.logEvent('Drive selector closed'); - this.setState({ - showDriveSelector: false, - }); - return; + done={async (drives: DrivelistDrive[]) => { + if (drives.length) { + await this.selectSource( + drives[0], + sourceDestination.BlockDevice, + ); } - await this.selectSource(drives[0], sourceDestination.BlockDevice); this.setState({ showDriveSelector: false, }); diff --git a/lib/gui/app/components/target-selector/target-selector-button.tsx b/lib/gui/app/components/target-selector/target-selector-button.tsx index f7abd371..00ea5b1f 100644 --- a/lib/gui/app/components/target-selector/target-selector-button.tsx +++ b/lib/gui/app/components/target-selector/target-selector-button.tsx @@ -15,14 +15,14 @@ */ import ExclamationTriangleSvg from '@fortawesome/fontawesome-free/svgs/solid/exclamation-triangle.svg'; -import { Drive as DrivelistDrive } from 'drivelist'; import * as React from 'react'; import { Flex, FlexProps, Txt } from 'rendition'; import { getDriveImageCompatibilityStatuses, - Image, + DriveStatus, } from '../../../../shared/drive-constraints'; +import { compatibility, warning } from '../../../../shared/messages'; import { bytesToClosestUnit } from '../../../../shared/units'; import { getSelectedDrives } from '../../models/selection-state'; import { @@ -41,40 +41,54 @@ interface TargetSelectorProps { flashing: boolean; show: boolean; tooltip: string; - image: Image; } -function DriveCompatibilityWarning({ - drive, - image, +function getDriveWarning(status: DriveStatus) { + switch (status.message) { + case compatibility.containsImage(): + return warning.sourceDrive(); + case compatibility.largeDrive(): + return warning.largeDriveSize(); + case compatibility.system(): + return warning.systemDrive(); + default: + return ''; + } +} + +const DriveCompatibilityWarning = ({ + warnings, ...props }: { - drive: DrivelistDrive; - image: Image; -} & FlexProps) { - const compatibilityWarnings = getDriveImageCompatibilityStatuses( - drive, - image, + warnings: string[]; +} & FlexProps) => { + const systemDrive = warnings.find( + (message) => message === warning.systemDrive(), ); - if (compatibilityWarnings.length === 0) { - return null; - } - const messages = compatibilityWarnings.map((warning) => warning.message); return ( - - + + ); -} +}; export function TargetSelectorButton(props: TargetSelectorProps) { const targets = getSelectedDrives(); if (targets.length === 1) { const target = targets[0]; + const warnings = getDriveImageCompatibilityStatuses(target).map( + getDriveWarning, + ); return ( <> + {warnings.length > 0 && ( + + )} {middleEllipsis(target.description, 20)} {!props.flashing && ( @@ -82,14 +96,7 @@ export function TargetSelectorButton(props: TargetSelectorProps) { Change )} - - - {bytesToClosestUnit(target.size)} - + {bytesToClosestUnit(target.size)} ); } @@ -97,6 +104,9 @@ export function TargetSelectorButton(props: TargetSelectorProps) { if (targets.length > 1) { const targetsTemplate = []; for (const target of targets) { + const warnings = getDriveImageCompatibilityStatuses(target).map( + getDriveWarning, + ); targetsTemplate.push( - + {warnings.length && ( + + )} {middleEllipsis(target.description, 14)} {bytesToClosestUnit(target.size)} , diff --git a/lib/gui/app/components/target-selector/target-selector.tsx b/lib/gui/app/components/target-selector/target-selector.tsx index 958e99f9..2ec79ddd 100644 --- a/lib/gui/app/components/target-selector/target-selector.tsx +++ b/lib/gui/app/components/target-selector/target-selector.tsx @@ -16,9 +16,8 @@ import { scanner } from 'etcher-sdk'; import * as React from 'react'; -import { Flex } from 'rendition'; -import { TargetSelector } from '../../components/target-selector/target-selector-button'; -import { TargetSelectorModal } from '../../components/target-selector/target-selector-modal'; +import { Flex, Txt } from 'rendition'; + import { DriveSelector, DriveSelectorProps, @@ -33,7 +32,10 @@ import { import * as settings from '../../models/settings'; import { observe } from '../../models/store'; import * as analytics from '../../modules/analytics'; +import { TargetSelectorButton } from './target-selector-button'; + import DriveSvg from '../../../assets/drive.svg'; +import { warning } from '../../../../shared/messages'; export const getDriveListLabel = () => { return getSelectedDrives() @@ -55,11 +57,18 @@ const getDriveSelectionStateSlice = () => ({ }); export const TargetSelectorModal = ( - props: Omit, + props: Omit< + DriveSelectorProps, + 'titleLabel' | 'emptyListLabel' | 'multipleSelection' + >, ) => ( ); @@ -106,7 +115,7 @@ export const TargetSelector = ({ }: TargetSelectorProps) => { // TODO: inject these from redux-connector const [ - { showDrivesButton, driveListLabel, targets, image }, + { showDrivesButton, driveListLabel, targets }, setStateSlice, ] = React.useState(getDriveSelectionStateSlice()); const [showTargetSelectorModal, setShowTargetSelectorModal] = React.useState( @@ -119,6 +128,7 @@ export const TargetSelector = ({ }); }, []); + const hasSystemDrives = targets.some((target) => target.isSystem); return ( + {hasSystemDrives ? ( + + Warning: {warning.systemDrive()} + + ) : null} + {showTargetSelectorModal && ( setShowTargetSelectorModal(false)} diff --git a/lib/gui/app/css/main.css b/lib/gui/app/css/main.css index b5350722..fcf89cf1 100644 --- a/lib/gui/app/css/main.css +++ b/lib/gui/app/css/main.css @@ -19,7 +19,6 @@ src: url("./fonts/SourceSansPro-Regular.ttf") format("truetype"); font-weight: 500; font-style: normal; - font-display: block; } @font-face { @@ -27,7 +26,6 @@ src: url("./fonts/SourceSansPro-SemiBold.ttf") format("truetype"); font-weight: 600; font-style: normal; - font-display: block; } html, @@ -53,10 +51,16 @@ body { a:focus, input:focus, button:focus, -[tabindex]:focus { +[tabindex]:focus, +input[type="checkbox"] + div { outline: none !important; + box-shadow: none !important; } .disabled { opacity: 0.4; } + +#rendition-tooltip-root > div { + font-family: "SourceSansPro", sans-serif; +} diff --git a/lib/gui/app/models/available-drives.ts b/lib/gui/app/models/available-drives.ts index 6389886f..7acc4a55 100644 --- a/lib/gui/app/models/available-drives.ts +++ b/lib/gui/app/models/available-drives.ts @@ -14,12 +14,10 @@ * limitations under the License. */ -import * as _ from 'lodash'; - import { Actions, store } from './store'; export function hasAvailableDrives() { - return !_.isEmpty(getDrives()); + return getDrives().length > 0; } export function setDrives(drives: any[]) { diff --git a/lib/gui/app/models/leds.ts b/lib/gui/app/models/leds.ts index 6478233e..5a31e3f3 100644 --- a/lib/gui/app/models/leds.ts +++ b/lib/gui/app/models/leds.ts @@ -14,11 +14,13 @@ * limitations under the License. */ -import { Drive as DrivelistDrive } from 'drivelist'; import * as _ from 'lodash'; import { AnimationFunction, Color, RGBLed } from 'sys-class-rgb-led'; -import { isSourceDrive } from '../../../shared/drive-constraints'; +import { + isSourceDrive, + DrivelistDrive, +} from '../../../shared/drive-constraints'; import * as settings from './settings'; import { DEFAULT_STATE, observe } from './store'; diff --git a/lib/gui/app/models/selection-state.ts b/lib/gui/app/models/selection-state.ts index 6843e256..06244e05 100644 --- a/lib/gui/app/models/selection-state.ts +++ b/lib/gui/app/models/selection-state.ts @@ -15,6 +15,7 @@ */ import * as _ from 'lodash'; +import { SourceMetadata } from '../components/source-selector/source-selector'; import * as availableDrives from './available-drives'; import { Actions, store } from './store'; @@ -67,7 +68,7 @@ export function getSelectedDrives(): any[] { /** * @summary Get the selected image */ -export function getImage() { +export function getImage(): SourceMetadata { return _.get(store.getState().toJS(), ['selection', 'image']); } @@ -114,7 +115,7 @@ export function hasDrive(): boolean { * @summary Check if there is a selected image */ export function hasImage(): boolean { - return Boolean(getImage()); + return !_.isEmpty(getImage()); } /** diff --git a/lib/gui/app/modules/image-writer.ts b/lib/gui/app/modules/image-writer.ts index e1ff0670..8091ede7 100644 --- a/lib/gui/app/modules/image-writer.ts +++ b/lib/gui/app/modules/image-writer.ts @@ -134,7 +134,7 @@ interface FlashResults { cancelled?: boolean; } -export async function performWrite( +async function performWrite( image: SourceMetadata, drives: DrivelistDrive[], onProgress: sdk.multiWrite.OnProgressFunction, diff --git a/lib/gui/app/modules/progress-status.ts b/lib/gui/app/modules/progress-status.ts index 4dcf9780..950ac463 100644 --- a/lib/gui/app/modules/progress-status.ts +++ b/lib/gui/app/modules/progress-status.ts @@ -51,7 +51,7 @@ export function fromFlashState({ } else { return { status: 'Flashing...', - position: `${bytesToClosestUnit(position)}`, + position: `${position ? bytesToClosestUnit(position) : ''}`, }; } } else if (type === 'verifying') { diff --git a/lib/gui/app/pages/main/Flash.tsx b/lib/gui/app/pages/main/Flash.tsx index 58ea0895..62ed0637 100644 --- a/lib/gui/app/pages/main/Flash.tsx +++ b/lib/gui/app/pages/main/Flash.tsx @@ -18,7 +18,7 @@ import CircleSvg from '@fortawesome/fontawesome-free/svgs/solid/circle.svg'; import * as _ from 'lodash'; import * as path from 'path'; import * as React from 'react'; -import { Flex, Modal, Txt } from 'rendition'; +import { Flex, Modal as SmallModal, Txt } from 'rendition'; import * as constraints from '../../../../shared/drive-constraints'; import * as messages from '../../../../shared/messages'; @@ -36,27 +36,11 @@ import { } from '../../components/target-selector/target-selector'; import FlashSvg from '../../../assets/flash.svg'; +import DriveStatusWarningModal from '../../components/drive-status-warning-modal/drive-status-warning-modal'; const COMPLETED_PERCENTAGE = 100; const SPEED_PRECISION = 2; -const getWarningMessages = (drives: any, image: any) => { - const warningMessages = []; - for (const drive of drives) { - if (constraints.isDriveSizeLarge(drive)) { - warningMessages.push(messages.warning.largeDriveSize(drive)); - } else if (!constraints.isDriveSizeRecommended(drive, image)) { - warningMessages.push( - messages.warning.unrecommendedDriveSize(image, drive), - ); - } - - // TODO(Shou): we should consider adding the same warning dialog for system drives and remove unsafe mode - } - - return warningMessages; -}; - const getErrorMessageFromCode = (errorCode: string) => { // TODO: All these error codes to messages translations // should go away if the writer emitted user friendly @@ -81,8 +65,8 @@ async function flashImageToDrive( ): Promise { const devices = selection.getSelectedDevices(); const image: any = selection.getImage(); - const drives = _.filter(availableDrives.getDrives(), (drive: any) => { - return _.includes(devices, drive.device); + const drives = availableDrives.getDrives().filter((drive: any) => { + return devices.includes(drive.device); }); if (drives.length === 0 || isFlashing) { @@ -132,7 +116,7 @@ async function flashImageToDrive( } const formatSeconds = (totalSeconds: number) => { - if (!totalSeconds && !_.isNumber(totalSeconds)) { + if (typeof totalSeconds !== 'number' || !Number.isFinite(totalSeconds)) { return ''; } const minutes = Math.floor(totalSeconds / 60); @@ -155,10 +139,16 @@ interface FlashStepProps { eta?: number; } +export interface DriveWithWarnings extends constraints.DrivelistDrive { + statuses: constraints.DriveStatus[]; +} + interface FlashStepState { - warningMessages: string[]; + warningMessage: boolean; errorMessage: string; showDriveSelectorModal: boolean; + systemDrives: boolean; + drivesWithWarnings: DriveWithWarnings[]; } export class FlashStep extends React.PureComponent< @@ -168,14 +158,16 @@ export class FlashStep extends React.PureComponent< constructor(props: FlashStepProps) { super(props); this.state = { - warningMessages: [], + warningMessage: false, errorMessage: '', showDriveSelectorModal: false, + systemDrives: false, + drivesWithWarnings: [], }; } private async handleWarningResponse(shouldContinue: boolean) { - this.setState({ warningMessages: [] }); + this.setState({ warningMessage: false }); if (!shouldContinue) { this.setState({ showDriveSelectorModal: true }); return; @@ -198,28 +190,45 @@ export class FlashStep extends React.PureComponent< } } - private hasListWarnings(drives: any[], image: any) { + private hasListWarnings(drives: any[]) { if (drives.length === 0 || flashState.isFlashing()) { return; } - return constraints.hasListDriveImageCompatibilityStatus(drives, image); + return drives.filter((drive) => drive.isSystem).length > 0; } private async tryFlash() { const devices = selection.getSelectedDevices(); - const image = selection.getImage(); - const drives = _.filter( - availableDrives.getDrives(), - (drive: { device: string }) => { - return _.includes(devices, drive.device); - }, - ); + const drives = availableDrives + .getDrives() + .filter((drive: { device: string }) => { + return devices.includes(drive.device); + }) + .map((drive) => { + return { + ...drive, + statuses: constraints.getDriveImageCompatibilityStatuses(drive), + }; + }); if (drives.length === 0 || this.props.isFlashing) { return; } - const hasDangerStatus = this.hasListWarnings(drives, image); + const hasDangerStatus = drives.some((drive) => drive.statuses.length > 0); if (hasDangerStatus) { - this.setState({ warningMessages: getWarningMessages(drives, image) }); + const systemDrives = drives.some((drive) => + drive.statuses.includes(constraints.statuses.system), + ); + this.setState({ + systemDrives, + drivesWithWarnings: drives.filter((driveWithWarnings) => { + return ( + driveWithWarnings.isSystem || + (!systemDrives && + driveWithWarnings.statuses.includes(constraints.statuses.large)) + ); + }), + warningMessage: true, + }); return; } this.setState({ @@ -253,13 +262,8 @@ export class FlashStep extends React.PureComponent< position={this.props.position} disabled={this.props.shouldFlashStepBeDisabled} cancel={imageWriter.cancel} - warning={this.hasListWarnings( - selection.getSelectedDrives(), - selection.getImage(), - )} - callback={() => { - this.tryFlash(); - }} + warning={this.hasListWarnings(selection.getSelectedDrives())} + callback={() => this.tryFlash()} /> {!_.isNil(this.props.speed) && @@ -270,9 +274,7 @@ export class FlashStep extends React.PureComponent< color="#7e8085" width="100%" > - {!_.isNil(this.props.speed) && ( - {this.props.speed.toFixed(SPEED_PRECISION)} MB/s - )} + {this.props.speed.toFixed(SPEED_PRECISION)} MB/s {!_.isNil(this.props.eta) && ( ETA: {formatSeconds(this.props.eta)} )} @@ -288,28 +290,17 @@ export class FlashStep extends React.PureComponent< )} - {this.state.warningMessages.length > 0 && ( - this.handleWarningResponse(false)} + {this.state.warningMessage && ( + this.handleWarningResponse(true)} - cancelButtonProps={{ - children: 'Change', - }} - action={'Continue'} - primaryButtonProps={{ primary: false, warning: true }} - > - {_.map(this.state.warningMessages, (message, key) => ( - - {message} - - ))} - + cancel={() => this.handleWarningResponse(false)} + isSystem={this.state.systemDrives} + drivesWithWarnings={this.state.drivesWithWarnings} + /> )} {this.state.errorMessage && ( - this.handleFlashErrorResponse(false)} @@ -317,11 +308,11 @@ export class FlashStep extends React.PureComponent< action={'Retry'} > - {_.map(this.state.errorMessage.split('\n'), (message, key) => ( + {this.state.errorMessage.split('\n').map((message, key) => (

{message}

))}
-
+ )} {this.state.showDriveSelectorModal && ( ( ))` color: #ffffff; + font-size: 14px; `; export const ChangeButton = styled(Button)` @@ -93,7 +95,7 @@ export const StepNameButton = styled(BaseButton)` justify-content: center; align-items: center; width: 100%; - font-weight: bold; + font-weight: normal; color: ${colors.dark.foreground}; &:enabled { @@ -119,6 +121,19 @@ export const DetailsText = (props: FlexProps) => ( /> ); +const modalFooterShadowCss = css` + overflow: auto; + background: 0, linear-gradient(rgba(255, 255, 255, 0), white 70%) 0 100%, 0, + linear-gradient(rgba(255, 255, 255, 0), rgba(221, 225, 240, 0.5) 70%) 0 100%; + background-repeat: no-repeat; + background-size: 100% 40px, 100% 40px, 100% 8px, 100% 8px; + + background-repeat: no-repeat; + background-color: white; + background-size: 100% 40px, 100% 40px, 100% 8px, 100% 8px; + background-attachment: local, local, scroll, scroll; +`; + export const Modal = styled(({ style, ...props }) => { return ( { > { }, }} style={{ - height: '86.5vh', + height: '87.5vh', ...style, }} {...props} @@ -157,27 +172,42 @@ export const Modal = styled(({ style, ...props }) => { ); })` > div { - padding: 24px 30px; - height: calc(100% - 80px); - - ::-webkit-scrollbar { - display: none; - } + padding: 0; + height: 100%; > h3 { margin: 0; + padding: 24px 30px 0; + height: 14.3%; + } + + > div:first-child { + height: 81%; + padding: 24px 30px 0; + } + + > div:nth-child(2) { + height: 61%; + + > div:not(.system-drive-alert) { + padding: 0 30px; + ${modalFooterShadowCss} + } } > div:last-child { + margin: 0; + flex-direction: ${(props) => + props.reverseFooterButtons ? 'row-reverse' : 'row'}; border-radius: 0 0 7px 7px; height: 80px; background-color: #fff; justify-content: center; - position: absolute; - bottom: 0; - left: 0; width: 100%; - box-shadow: 0 -2px 10px 0 rgba(221, 225, 240, 0.5), 0 -1px 0 0 #dde1f0; + } + + ::-webkit-scrollbar { + display: none; } } `; @@ -194,3 +224,28 @@ export const ScrollableFlex = styled(Flex)` overflow-x: visible; } `; + +export const Alert = styled((props) => ( + +))` + position: fixed; + top: -40px; + left: 50%; + transform: translate(-50%, 0px); + height: 30px; + min-width: 50%; + padding: 0px; + justify-content: center; + align-items: center; + font-size: 14px; + background-color: #fca321; + text-align: center; + + * { + color: #ffffff; + } + + > div:first-child { + display: none; + } +`; diff --git a/lib/gui/app/theme.ts b/lib/gui/app/theme.ts index 20ab7c32..e6a4ae95 100644 --- a/lib/gui/app/theme.ts +++ b/lib/gui/app/theme.ts @@ -90,20 +90,21 @@ export const theme = { opacity: 1, }, extend: () => ` - && { - width: 200px; - height: 48px; - font-size: 16px; + width: 200px; + font-size: 16px; - :disabled { + && { + height: 48px; + } + + :disabled { + background-color: ${colors.dark.disabled.background}; + color: ${colors.dark.disabled.foreground}; + opacity: 1; + + :hover { background-color: ${colors.dark.disabled.background}; color: ${colors.dark.disabled.foreground}; - opacity: 1; - - :hover { - background-color: ${colors.dark.disabled.background}; - color: ${colors.dark.disabled.foreground}; - } } } `, diff --git a/lib/gui/modules/child-writer.ts b/lib/gui/modules/child-writer.ts index 61fafe72..1f60fdd7 100644 --- a/lib/gui/modules/child-writer.ts +++ b/lib/gui/modules/child-writer.ts @@ -229,6 +229,7 @@ ipc.connectTo(IPC_SERVER_ID, () => { const destinations = options.destinations.map((d) => d.device); const imagePath = options.image.path; + log(`Image: ${imagePath}`); log(`Devices: ${destinations.join(', ')}`); log(`Umount on success: ${options.unmountOnSuccess}`); log(`Validate on success: ${options.validateWriteOnSuccess}`); @@ -248,7 +249,6 @@ ipc.connectTo(IPC_SERVER_ID, () => { if (options.image.drive) { source = new BlockDevice({ drive: options.image.drive, - write: false, direct: !options.autoBlockmapping, }); } else { diff --git a/lib/shared/drive-constraints.ts b/lib/shared/drive-constraints.ts index f8630de8..c75bd719 100644 --- a/lib/shared/drive-constraints.ts +++ b/lib/shared/drive-constraints.ts @@ -14,10 +14,9 @@ * limitations under the License. */ -import { Drive as DrivelistDrive } from 'drivelist'; +import { Drive } from 'drivelist'; import * as _ from 'lodash'; import * as pathIsInside from 'path-is-inside'; -import * as prettyBytes from 'pretty-bytes'; import * as messages from './messages'; import { SourceMetadata } from '../gui/app/components/source-selector/source-selector'; @@ -27,6 +26,14 @@ import { SourceMetadata } from '../gui/app/components/source-selector/source-sel */ const UNKNOWN_SIZE = 0; +export type DrivelistDrive = Drive & { + disabled: boolean; + name: string; + path: string; + logo: string; + displayName: string; +}; + /** * @summary Check if a drive is locked * @@ -34,22 +41,14 @@ const UNKNOWN_SIZE = 0; * This usually points out a locked SD Card. */ export function isDriveLocked(drive: DrivelistDrive): boolean { - return Boolean(_.get(drive, ['isReadOnly'], false)); + return Boolean(drive.isReadOnly); } /** * @summary Check if a drive is a system drive */ export function isSystemDrive(drive: DrivelistDrive): boolean { - return Boolean(_.get(drive, ['isSystem'], false)); -} - -export interface Image { - path: string; - isSizeEstimated?: boolean; - compressedSize?: number; - recommendedDriveSize?: number; - size?: number; + return Boolean(drive.isSystem); } function sourceIsInsideDrive(source: string, drive: DrivelistDrive) { @@ -89,17 +88,21 @@ export function isSourceDrive( * @summary Check if a drive is large enough for an image */ export function isDriveLargeEnough( - drive: DrivelistDrive | undefined, - image: Image, + drive: DrivelistDrive, + image?: SourceMetadata, ): boolean { - const driveSize = _.get(drive, 'size') || UNKNOWN_SIZE; + const driveSize = drive.size || UNKNOWN_SIZE; - if (_.get(image, ['isSizeEstimated'])) { + if (image === undefined) { + return true; + } + + if (image.isSizeEstimated) { // If the drive size is smaller than the original image size, and // the final image size is just an estimation, then we stop right // here, based on the assumption that the final size will never // be less than the original size. - if (driveSize < _.get(image, ['compressedSize'], UNKNOWN_SIZE)) { + if (driveSize < (image.compressedSize || UNKNOWN_SIZE)) { return false; } @@ -110,20 +113,23 @@ export function isDriveLargeEnough( return true; } - return driveSize >= _.get(image, ['size'], UNKNOWN_SIZE); + return driveSize >= (image.size || UNKNOWN_SIZE); } /** * @summary Check if a drive is disabled (i.e. not ready for selection) */ export function isDriveDisabled(drive: DrivelistDrive): boolean { - return _.get(drive, ['disabled'], false); + return drive.disabled || false; } /** * @summary Check if a drive is valid, i.e. not locked and large enough for an image */ -export function isDriveValid(drive: DrivelistDrive, image: Image): boolean { +export function isDriveValid( + drive: DrivelistDrive, + image?: SourceMetadata, +): boolean { return ( !isDriveLocked(drive) && isDriveLargeEnough(drive, image) && @@ -139,23 +145,23 @@ export function isDriveValid(drive: DrivelistDrive, image: Image): boolean { * If the image doesn't have a recommended size, this function returns true. */ export function isDriveSizeRecommended( - drive: DrivelistDrive | undefined, - image: Image, + drive: DrivelistDrive, + image?: SourceMetadata, ): boolean { - const driveSize = _.get(drive, 'size') || UNKNOWN_SIZE; - return driveSize >= _.get(image, ['recommendedDriveSize'], UNKNOWN_SIZE); + const driveSize = drive.size || UNKNOWN_SIZE; + return driveSize >= (image?.recommendedDriveSize || UNKNOWN_SIZE); } /** - * @summary 64GB + * @summary 128GB */ -export const LARGE_DRIVE_SIZE = 64e9; +export const LARGE_DRIVE_SIZE = 128e9; /** * @summary Check whether a drive's size is 'large' */ -export function isDriveSizeLarge(drive?: DrivelistDrive): boolean { - const driveSize = _.get(drive, 'size') || UNKNOWN_SIZE; +export function isDriveSizeLarge(drive: DrivelistDrive): boolean { + const driveSize = drive.size || UNKNOWN_SIZE; return driveSize > LARGE_DRIVE_SIZE; } @@ -170,6 +176,33 @@ export const COMPATIBILITY_STATUS_TYPES = { ERROR: 2, }; +export const statuses = { + locked: { + type: COMPATIBILITY_STATUS_TYPES.ERROR, + message: messages.compatibility.locked(), + }, + system: { + type: COMPATIBILITY_STATUS_TYPES.WARNING, + message: messages.compatibility.system(), + }, + containsImage: { + type: COMPATIBILITY_STATUS_TYPES.ERROR, + message: messages.compatibility.containsImage(), + }, + large: { + type: COMPATIBILITY_STATUS_TYPES.WARNING, + message: messages.compatibility.largeDrive(), + }, + small: { + type: COMPATIBILITY_STATUS_TYPES.ERROR, + message: messages.compatibility.tooSmall(), + }, + sizeNotRecommended: { + type: COMPATIBILITY_STATUS_TYPES.WARNING, + message: messages.compatibility.sizeNotRecommended(), + }, +}; + /** * @summary Get drive/image compatibility in an object * @@ -182,7 +215,7 @@ export const COMPATIBILITY_STATUS_TYPES = { */ export function getDriveImageCompatibilityStatuses( drive: DrivelistDrive, - image: Image, + image?: SourceMetadata, ) { const statusList = []; @@ -197,41 +230,25 @@ export function getDriveImageCompatibilityStatuses( !_.isNil(drive.size) && !isDriveLargeEnough(drive, image) ) { - const imageSize = (image.isSizeEstimated - ? image.compressedSize - : image.size) as number; - const relativeBytes = imageSize - drive.size; - statusList.push({ - type: COMPATIBILITY_STATUS_TYPES.ERROR, - message: messages.compatibility.tooSmall(prettyBytes(relativeBytes)), - }); + statusList.push(statuses.small); } else { - if (isSourceDrive(drive, image as SourceMetadata)) { - statusList.push({ - type: COMPATIBILITY_STATUS_TYPES.ERROR, - message: messages.compatibility.containsImage(), - }); - } - + // Avoid showing "large drive" with "system drive" status if (isSystemDrive(drive)) { - statusList.push({ - type: COMPATIBILITY_STATUS_TYPES.WARNING, - message: messages.compatibility.system(), - }); + statusList.push(statuses.system); + } else if (isDriveSizeLarge(drive)) { + statusList.push(statuses.large); } - if (isDriveSizeLarge(drive)) { - statusList.push({ - type: COMPATIBILITY_STATUS_TYPES.WARNING, - message: messages.compatibility.largeDrive(), - }); + if (isSourceDrive(drive, image as SourceMetadata)) { + statusList.push(statuses.containsImage); } - if (!_.isNil(drive) && !isDriveSizeRecommended(drive, image)) { - statusList.push({ - type: COMPATIBILITY_STATUS_TYPES.WARNING, - message: messages.compatibility.sizeNotRecommended(), - }); + if ( + image !== undefined && + !_.isNil(drive) && + !isDriveSizeRecommended(drive, image) + ) { + statusList.push(statuses.sizeNotRecommended); } } @@ -247,9 +264,9 @@ export function getDriveImageCompatibilityStatuses( */ export function getListDriveImageCompatibilityStatuses( drives: DrivelistDrive[], - image: Image, + image: SourceMetadata, ) { - return _.flatMap(drives, (drive) => { + return drives.flatMap((drive) => { return getDriveImageCompatibilityStatuses(drive, image); }); } @@ -262,35 +279,11 @@ export function getListDriveImageCompatibilityStatuses( */ export function hasDriveImageCompatibilityStatus( drive: DrivelistDrive, - image: Image, + image: SourceMetadata, ) { return Boolean(getDriveImageCompatibilityStatuses(drive, image).length); } -/** - * @summary Does any drive/image pair have at least one compatibility status? - * @function - * @public - * - * @description - * Given an image and a drive, return whether they have a connected compatibility status object. - * - * @param {Object[]} drives - drives - * @param {Object} image - image - * @returns {Boolean} - * - * @example - * if (constraints.hasDriveImageCompatibilityStatus(drive, image)) { - * console.log('This drive-image pair has a compatibility status message!') - * } - */ -export function hasListDriveImageCompatibilityStatus( - drives: DrivelistDrive[], - image: Image, -) { - return Boolean(getListDriveImageCompatibilityStatuses(drives, image).length); -} - export interface DriveStatus { message: string; type: number; diff --git a/lib/shared/messages.ts b/lib/shared/messages.ts index 500c3468..b3cd838b 100644 --- a/lib/shared/messages.ts +++ b/lib/shared/messages.ts @@ -15,6 +15,7 @@ */ import { Dictionary } from 'lodash'; +import * as prettyBytes from 'pretty-bytes'; export const progress: Dictionary<(quantity: number) => string> = { successful: (quantity: number) => { @@ -53,11 +54,11 @@ export const info = { export const compatibility = { sizeNotRecommended: () => { - return 'Not Recommended'; + return 'Not recommended'; }, - tooSmall: (additionalSpace: string) => { - return `Insufficient space, additional ${additionalSpace} required`; + tooSmall: () => { + return 'Too small'; }, locked: () => { @@ -84,8 +85,8 @@ export const warning = { drive: { device: string; size: number }, ) => { return [ - `This image recommends a ${image.recommendedDriveSize}`, - `bytes drive, however ${drive.device} is only ${drive.size} bytes.`, + `This image recommends a ${prettyBytes(image.recommendedDriveSize)}`, + `drive, however ${drive.device} is only ${prettyBytes(drive.size)}.`, ].join(' '); }, @@ -115,11 +116,16 @@ export const warning = { ].join(' '); }, - largeDriveSize: (drive: { description: string; device: string }) => { - return [ - `Drive ${drive.description} (${drive.device}) is unusually large for an SD card or USB stick.`, - '\n\nAre you sure you want to flash this drive?', - ].join(' '); + largeDriveSize: () => { + return 'This is a large drive! Make sure it doesn\'t contain files that you want to keep.'; + }, + + systemDrive: () => { + return 'Selecting your system drive is dangerous and will erase your drive!'; + }, + + sourceDrive: () => { + return 'Contains the image you chose to flash'; }, }; diff --git a/lib/shared/units.ts b/lib/shared/units.ts index dcf3646c..daae6707 100644 --- a/lib/shared/units.ts +++ b/lib/shared/units.ts @@ -23,9 +23,6 @@ export function bytesToMegabytes(bytes: number): number { return bytes / MEGABYTE_TO_BYTE_RATIO; } -export function bytesToClosestUnit(bytes: number): string | null { - if (_.isNumber(bytes)) { - return prettyBytes(bytes); - } - return null; +export function bytesToClosestUnit(bytes: number): string { + return prettyBytes(bytes); } diff --git a/tests/gui/modules/image-writer.spec.ts b/tests/gui/modules/image-writer.spec.ts index 677b2f6c..4b38c844 100644 --- a/tests/gui/modules/image-writer.spec.ts +++ b/tests/gui/modules/image-writer.spec.ts @@ -20,6 +20,7 @@ import { sourceDestination } from 'etcher-sdk'; import * as ipc from 'node-ipc'; import { assert, SinonStub, stub } from 'sinon'; +import { SourceMetadata } from '../../../lib/gui/app/components/source-selector/source-selector'; import * as flashState from '../../../lib/gui/app/models/flash-state'; import * as imageWriter from '../../../lib/gui/app/modules/image-writer'; @@ -28,9 +29,11 @@ const fakeDrive: DrivelistDrive = {}; describe('Browser: imageWriter', () => { describe('.flash()', () => { - const image = { + const image: SourceMetadata = { hasMBR: false, partitions: [], + description: 'foo.img', + displayName: 'foo.img', path: 'foo.img', SourceType: sourceDestination.File, extension: 'img', @@ -60,7 +63,7 @@ describe('Browser: imageWriter', () => { }); try { - imageWriter.flash(image, [fakeDrive], performWriteStub); + await imageWriter.flash(image, [fakeDrive], performWriteStub); } catch { // noop } finally { diff --git a/tests/shared/drive-constraints.spec.ts b/tests/shared/drive-constraints.spec.ts index 62687fde..d557f905 100644 --- a/tests/shared/drive-constraints.spec.ts +++ b/tests/shared/drive-constraints.spec.ts @@ -15,10 +15,9 @@ */ import { expect } from 'chai'; -import { Drive as DrivelistDrive } from 'drivelist'; import { sourceDestination } from 'etcher-sdk'; -import * as _ from 'lodash'; import * as path from 'path'; +import { SourceMetadata } from '../../lib/gui/app/components/source-selector/source-selector'; import * as constraints from '../../lib/shared/drive-constraints'; import * as messages from '../../lib/shared/messages'; @@ -30,7 +29,7 @@ describe('Shared: DriveConstraints', function () { device: '/dev/disk2', size: 999999999, isReadOnly: true, - } as DrivelistDrive); + } as constraints.DrivelistDrive); expect(result).to.be.true; }); @@ -40,7 +39,7 @@ describe('Shared: DriveConstraints', function () { device: '/dev/disk2', size: 999999999, isReadOnly: false, - } as DrivelistDrive); + } as constraints.DrivelistDrive); expect(result).to.be.false; }); @@ -49,16 +48,10 @@ describe('Shared: DriveConstraints', function () { const result = constraints.isDriveLocked({ device: '/dev/disk2', size: 999999999, - } as DrivelistDrive); + } as constraints.DrivelistDrive); expect(result).to.be.false; }); - - it('should return false if the drive is undefined', function () { - // @ts-ignore - const result = constraints.isDriveLocked(undefined); - expect(result).to.be.false; - }); }); describe('.isSystemDrive()', function () { @@ -68,7 +61,7 @@ describe('Shared: DriveConstraints', function () { size: 999999999, isReadOnly: true, isSystem: true, - } as DrivelistDrive); + } as constraints.DrivelistDrive); expect(result).to.be.true; }); @@ -78,7 +71,7 @@ describe('Shared: DriveConstraints', function () { device: '/dev/disk2', size: 999999999, isReadOnly: true, - } as DrivelistDrive); + } as constraints.DrivelistDrive); expect(result).to.be.false; }); @@ -89,16 +82,10 @@ describe('Shared: DriveConstraints', function () { size: 999999999, isReadOnly: true, isSystem: false, - } as DrivelistDrive); + } as constraints.DrivelistDrive); expect(result).to.be.false; }); - - it('should return false if the drive is undefined', function () { - // @ts-ignore - const result = constraints.isSystemDrive(undefined); - expect(result).to.be.false; - }); }); describe('.isSourceDrive()', function () { @@ -109,7 +96,7 @@ describe('Shared: DriveConstraints', function () { size: 999999999, isReadOnly: true, isSystem: false, - } as DrivelistDrive, + } as constraints.DrivelistDrive, // @ts-ignore undefined, ); @@ -124,8 +111,10 @@ describe('Shared: DriveConstraints', function () { size: 999999999, isReadOnly: true, isSystem: false, - } as DrivelistDrive, + } as constraints.DrivelistDrive, { + description: 'image.img', + displayName: 'image.img', path: '/Volumes/Untitled/image.img', hasMBR: false, partitions: [], @@ -137,6 +126,14 @@ describe('Shared: DriveConstraints', function () { }); describe('given Windows paths', function () { + const windowsImage: SourceMetadata = { + description: 'image.img', + displayName: 'image.img', + path: 'E:\\image.img', + hasMBR: false, + partitions: [], + SourceType: sourceDestination.File, + }; beforeEach(function () { this.separator = path.sep; // @ts-ignore @@ -161,13 +158,8 @@ describe('Shared: DriveConstraints', function () { path: 'F:', }, ], - } as DrivelistDrive, - { - path: 'E:\\image.img', - hasMBR: false, - partitions: [], - SourceType: sourceDestination.File, - }, + } as constraints.DrivelistDrive, + windowsImage, ); expect(result).to.be.true; @@ -186,12 +178,10 @@ describe('Shared: DriveConstraints', function () { path: 'F:', }, ], - } as DrivelistDrive, + } as constraints.DrivelistDrive, { + ...windowsImage, path: 'E:\\foo\\bar\\image.img', - hasMBR: false, - partitions: [], - SourceType: sourceDestination.File, }, ); @@ -211,12 +201,10 @@ describe('Shared: DriveConstraints', function () { path: 'F:', }, ], - } as DrivelistDrive, + } as constraints.DrivelistDrive, { + ...windowsImage, path: 'G:\\image.img', - hasMBR: false, - partitions: [], - SourceType: sourceDestination.File, }, ); @@ -232,12 +220,10 @@ describe('Shared: DriveConstraints', function () { path: 'E:\\fo', }, ], - } as DrivelistDrive, + } as constraints.DrivelistDrive, { + ...windowsImage, path: 'E:\\foo/image.img', - hasMBR: false, - partitions: [], - SourceType: sourceDestination.File, }, ); @@ -246,6 +232,14 @@ describe('Shared: DriveConstraints', function () { }); describe('given UNIX paths', function () { + const image: SourceMetadata = { + description: 'image.img', + displayName: 'image.img', + path: '/Volumes/Untitled/image.img', + hasMBR: false, + partitions: [], + SourceType: sourceDestination.File, + }; beforeEach(function () { this.separator = path.sep; // @ts-ignore @@ -265,12 +259,10 @@ describe('Shared: DriveConstraints', function () { path: '/', }, ], - } as DrivelistDrive, + } as constraints.DrivelistDrive, { + ...image, path: '/image.img', - hasMBR: false, - partitions: [], - SourceType: sourceDestination.File, }, ); @@ -288,12 +280,10 @@ describe('Shared: DriveConstraints', function () { path: '/Volumes/B', }, ], - } as DrivelistDrive, + } as constraints.DrivelistDrive, { + ...image, path: '/Volumes/A/image.img', - hasMBR: false, - partitions: [], - SourceType: sourceDestination.File, }, ); @@ -311,12 +301,10 @@ describe('Shared: DriveConstraints', function () { path: '/Volumes/B', }, ], - } as DrivelistDrive, + } as constraints.DrivelistDrive, { + ...image, path: '/Volumes/A/foo/bar/image.img', - hasMBR: false, - partitions: [], - SourceType: sourceDestination.File, }, ); @@ -334,12 +322,10 @@ describe('Shared: DriveConstraints', function () { path: '/Volumes/B', }, ], - } as DrivelistDrive, + } as constraints.DrivelistDrive, { + ...image, path: '/Volumes/C/image.img', - hasMBR: false, - partitions: [], - SourceType: sourceDestination.File, }, ); @@ -354,12 +340,10 @@ describe('Shared: DriveConstraints', function () { path: '/Volumes/fo', }, ], - } as DrivelistDrive, + } as constraints.DrivelistDrive, { + ...image, path: '/Volumes/foo/image.img', - hasMBR: false, - partitions: [], - SourceType: sourceDestination.File, }, ); @@ -546,35 +530,19 @@ describe('Shared: DriveConstraints', function () { }); }); - it('should return false if the drive is undefined', function () { - const result = constraints.isDriveLargeEnough(undefined, { - path: path.join(__dirname, 'rpi.img'), - size: 1000000000, - isSizeEstimated: false, - }); - - expect(result).to.be.false; - }); - it('should return true if the image is undefined', function () { const result = constraints.isDriveLargeEnough( { device: '/dev/disk1', size: 1000000000, isReadOnly: false, - } as DrivelistDrive, + } as constraints.DrivelistDrive, // @ts-ignore undefined, ); expect(result).to.be.true; }); - - it('should return false if the drive and image are undefined', function () { - // @ts-ignore - const result = constraints.isDriveLargeEnough(undefined, undefined); - expect(result).to.be.true; - }); }); describe('.isDriveDisabled()', function () { @@ -584,7 +552,7 @@ describe('Shared: DriveConstraints', function () { size: 1000000000, isReadOnly: false, disabled: true, - } as unknown) as DrivelistDrive); + } as unknown) as constraints.DrivelistDrive); expect(result).to.be.true; }); @@ -595,7 +563,7 @@ describe('Shared: DriveConstraints', function () { size: 1000000000, isReadOnly: false, disabled: false, - } as unknown) as DrivelistDrive); + } as unknown) as constraints.DrivelistDrive); expect(result).to.be.false; }); @@ -605,26 +573,30 @@ describe('Shared: DriveConstraints', function () { device: '/dev/disk1', size: 1000000000, isReadOnly: false, - } as DrivelistDrive); + } as constraints.DrivelistDrive); expect(result).to.be.false; }); }); describe('.isDriveSizeRecommended()', function () { + const image: SourceMetadata = { + description: 'rpi.img', + displayName: 'rpi.img', + path: path.join(__dirname, 'rpi.img'), + size: 1000000000, + isSizeEstimated: false, + recommendedDriveSize: 2000000000, + SourceType: sourceDestination.File, + }; it('should return true if the drive size is greater than the recommended size ', function () { const result = constraints.isDriveSizeRecommended( { device: '/dev/disk1', size: 2000000001, isReadOnly: false, - } as DrivelistDrive, - { - path: path.join(__dirname, 'rpi.img'), - size: 1000000000, - isSizeEstimated: false, - recommendedDriveSize: 2000000000, - }, + } as constraints.DrivelistDrive, + image, ); expect(result).to.be.true; @@ -636,13 +608,8 @@ describe('Shared: DriveConstraints', function () { device: '/dev/disk1', size: 2000000000, isReadOnly: false, - } as DrivelistDrive, - { - path: path.join(__dirname, 'rpi.img'), - size: 1000000000, - isSizeEstimated: false, - recommendedDriveSize: 2000000000, - }, + } as constraints.DrivelistDrive, + image, ); expect(result).to.be.true; @@ -654,11 +621,9 @@ describe('Shared: DriveConstraints', function () { device: '/dev/disk1', size: 2000000000, isReadOnly: false, - } as DrivelistDrive, + } as constraints.DrivelistDrive, { - path: path.join(__dirname, 'rpi.img'), - size: 1000000000, - isSizeEstimated: false, + ...image, recommendedDriveSize: 2000000001, }, ); @@ -672,47 +637,29 @@ describe('Shared: DriveConstraints', function () { device: '/dev/disk1', size: 2000000000, isReadOnly: false, - } as DrivelistDrive, + } as constraints.DrivelistDrive, { - path: path.join(__dirname, 'rpi.img'), - size: 1000000000, - isSizeEstimated: false, + ...image, + recommendedDriveSize: undefined, }, ); expect(result).to.be.true; }); - it('should return false if the drive is undefined', function () { - const result = constraints.isDriveSizeRecommended(undefined, { - path: path.join(__dirname, 'rpi.img'), - size: 1000000000, - isSizeEstimated: false, - recommendedDriveSize: 1000000000, - }); - - expect(result).to.be.false; - }); - it('should return true if the image is undefined', function () { const result = constraints.isDriveSizeRecommended( { device: '/dev/disk1', size: 2000000000, isReadOnly: false, - } as DrivelistDrive, + } as constraints.DrivelistDrive, // @ts-ignore undefined, ); expect(result).to.be.true; }); - - it('should return false if the drive and image are undefined', function () { - // @ts-ignore - const result = constraints.isDriveSizeRecommended(undefined, undefined); - expect(result).to.be.true; - }); }); describe('.isDriveValid()', function () { @@ -740,16 +687,29 @@ describe('Shared: DriveConstraints', function () { }); describe('given the drive is disabled', function () { + const image: SourceMetadata = { + description: 'rpi.img', + displayName: 'rpi.img', + path: '', + SourceType: sourceDestination.File, + size: 2000000000, + isSizeEstimated: false, + }; beforeEach(function () { this.drive.disabled = true; }); it('should return false if the drive is not large enough and is a source drive', function () { + console.log('YAYYY', { + ...image, + path: path.join(this.mountpoint, 'rpi.img'), + size: 5000000000, + }); expect( constraints.isDriveValid(this.drive, { + ...image, path: path.join(this.mountpoint, 'rpi.img'), size: 5000000000, - isSizeEstimated: false, }), ).to.be.false; }); @@ -757,35 +717,35 @@ describe('Shared: DriveConstraints', function () { it('should return false if the drive is not large enough and is not a source drive', function () { expect( constraints.isDriveValid(this.drive, { + ...image, path: path.resolve(this.mountpoint, '../bar/rpi.img'), - size: 5000000000, - isSizeEstimated: false, }), ).to.be.false; }); it('should return false if the drive is large enough and is a source drive', function () { - expect( - constraints.isDriveValid(this.drive, { - path: path.join(this.mountpoint, 'rpi.img'), - size: 2000000000, - isSizeEstimated: false, - }), - ).to.be.false; + expect(constraints.isDriveValid(this.drive, image)).to.be.false; }); it('should return false if the drive is large enough and is not a source drive', function () { expect( constraints.isDriveValid(this.drive, { + ...image, path: path.resolve(this.mountpoint, '../bar/rpi.img'), - size: 2000000000, - isSizeEstimated: false, }), ).to.be.false; }); }); describe('given the drive is not disabled', function () { + const image: SourceMetadata = { + description: 'rpi.img', + displayName: 'rpi.img', + path: '', + SourceType: sourceDestination.File, + size: 2000000000, + isSizeEstimated: false, + }; beforeEach(function () { this.drive.disabled = false; }); @@ -793,9 +753,9 @@ describe('Shared: DriveConstraints', function () { it('should return false if the drive is not large enough and is a source drive', function () { expect( constraints.isDriveValid(this.drive, { + ...image, path: path.join(this.mountpoint, 'rpi.img'), size: 5000000000, - isSizeEstimated: false, }), ).to.be.false; }); @@ -803,29 +763,22 @@ describe('Shared: DriveConstraints', function () { it('should return false if the drive is not large enough and is not a source drive', function () { expect( constraints.isDriveValid(this.drive, { + ...image, path: path.resolve(this.mountpoint, '../bar/rpi.img'), size: 5000000000, - isSizeEstimated: false, }), ).to.be.false; }); it('should return false if the drive is large enough and is a source drive', function () { - expect( - constraints.isDriveValid(this.drive, { - path: path.join(this.mountpoint, 'rpi.img'), - size: 2000000000, - isSizeEstimated: false, - }), - ).to.be.false; + expect(constraints.isDriveValid(this.drive, image)).to.be.false; }); it('should return false if the drive is large enough and is not a source drive', function () { expect( constraints.isDriveValid(this.drive, { + ...image, path: path.resolve(this.mountpoint, '../bar/rpi.img'), - size: 2000000000, - isSizeEstimated: false, }), ).to.be.false; }); @@ -833,6 +786,14 @@ describe('Shared: DriveConstraints', function () { }); describe('given the drive is not locked', function () { + const image: SourceMetadata = { + description: 'rpi.img', + displayName: 'rpi.img', + path: '', + SourceType: sourceDestination.File, + size: 2000000000, + isSizeEstimated: false, + }; beforeEach(function () { this.drive.isReadOnly = false; }); @@ -845,9 +806,9 @@ describe('Shared: DriveConstraints', function () { it('should return false if the drive is not large enough and is a source drive', function () { expect( constraints.isDriveValid(this.drive, { + ...image, path: path.join(this.mountpoint, 'rpi.img'), size: 5000000000, - isSizeEstimated: false, }), ).to.be.false; }); @@ -855,29 +816,22 @@ describe('Shared: DriveConstraints', function () { it('should return false if the drive is not large enough and is not a source drive', function () { expect( constraints.isDriveValid(this.drive, { + ...image, path: path.resolve(this.mountpoint, '../bar/rpi.img'), size: 5000000000, - isSizeEstimated: false, }), ).to.be.false; }); it('should return false if the drive is large enough and is a source drive', function () { - expect( - constraints.isDriveValid(this.drive, { - path: path.join(this.mountpoint, 'rpi.img'), - size: 2000000000, - isSizeEstimated: false, - }), - ).to.be.false; + expect(constraints.isDriveValid(this.drive, image)).to.be.false; }); it('should return false if the drive is large enough and is not a source drive', function () { expect( constraints.isDriveValid(this.drive, { + ...image, path: path.resolve(this.mountpoint, '../bar/rpi.img'), - size: 2000000000, - isSizeEstimated: false, }), ).to.be.false; }); @@ -891,9 +845,9 @@ describe('Shared: DriveConstraints', function () { it('should return false if the drive is not large enough and is a source drive', function () { expect( constraints.isDriveValid(this.drive, { + ...image, path: path.join(this.mountpoint, 'rpi.img'), size: 5000000000, - isSizeEstimated: false, }), ).to.be.false; }); @@ -901,9 +855,9 @@ describe('Shared: DriveConstraints', function () { it('should return false if the drive is not large enough and is not a source drive', function () { expect( constraints.isDriveValid(this.drive, { + ...image, path: path.resolve(this.mountpoint, '../bar/rpi.img'), size: 5000000000, - isSizeEstimated: false, }), ).to.be.false; }); @@ -911,9 +865,8 @@ describe('Shared: DriveConstraints', function () { it('should return false if the drive is large enough and is a source drive', function () { expect( constraints.isDriveValid(this.drive, { + ...image, path: path.join(this.mountpoint, 'rpi.img'), - size: 2000000000, - isSizeEstimated: false, }), ).to.be.false; }); @@ -921,9 +874,8 @@ describe('Shared: DriveConstraints', function () { it('should return true if the drive is large enough and is not a source drive', function () { expect( constraints.isDriveValid(this.drive, { + ...image, path: path.resolve(this.mountpoint, '../bar/rpi.img'), - size: 2000000000, - isSizeEstimated: false, }), ).to.be.true; }); @@ -947,6 +899,7 @@ describe('Shared: DriveConstraints', function () { }; this.image = { + SourceType: sourceDestination.File, path: path.join(__dirname, 'rpi.img'), size: this.drive.size - 1, isSizeEstimated: false, @@ -991,28 +944,41 @@ describe('Shared: DriveConstraints', function () { }; this.image = { + SourceType: sourceDestination.File, path: path.join(__dirname, 'rpi.img'), size: this.drive.size - 1, isSizeEstimated: false, }; }); + const compareTuplesMessages = ( + tuple1: { message: string }, + tuple2: { message: string }, + ) => { + if (tuple1.message.toLowerCase() === tuple2.message.toLowerCase()) { + return 0; + } + return tuple1.message.toLowerCase() > tuple2.message.toLowerCase() + ? 1 + : -1; + }; + const expectStatusTypesAndMessagesToBe = ( resultList: Array<{ message: string }>, expectedTuples: Array<['WARNING' | 'ERROR', string]>, + params?: number, ) => { // Sort so that order doesn't matter - const expectedTuplesSorted = _.sortBy( - _.map(expectedTuples, (tuple) => { + const expectedTuplesSorted = expectedTuples + .map((tuple) => { return { type: constraints.COMPATIBILITY_STATUS_TYPES[tuple[0]], // @ts-ignore - message: messages.compatibility[tuple[1]](), + message: messages.compatibility[tuple[1]](params), }; - }), - ['message'], - ); - const resultTuplesSorted = _.sortBy(resultList, ['message']); + }) + .sort(compareTuplesMessages); + const resultTuplesSorted = resultList.sort(compareTuplesMessages); expect(resultTuplesSorted).to.deep.equal(expectedTuplesSorted); }; @@ -1082,7 +1048,7 @@ describe('Shared: DriveConstraints', function () { ); const expected = [ { - message: messages.compatibility.tooSmall('1 B'), + message: messages.compatibility.tooSmall(), type: constraints.COMPATIBILITY_STATUS_TYPES.ERROR, }, ]; @@ -1148,11 +1114,14 @@ describe('Shared: DriveConstraints', function () { this.drive, this.image, ); - // @ts-ignore const expectedTuples = [['WARNING', 'largeDrive']]; - // @ts-ignore - expectStatusTypesAndMessagesToBe(result, expectedTuples); + expectStatusTypesAndMessagesToBe( + result, + // @ts-ignore + expectedTuples, + this.drive.size, + ); }); }); @@ -1200,7 +1169,7 @@ describe('Shared: DriveConstraints', function () { ); const expected = [ { - message: messages.compatibility.tooSmall('1 B'), + message: messages.compatibility.tooSmall(), type: constraints.COMPATIBILITY_STATUS_TYPES.ERROR, }, ]; @@ -1251,7 +1220,7 @@ describe('Shared: DriveConstraints', function () { mountpoints: [{ path: __dirname }], isSystem: false, isReadOnly: false, - } as unknown) as DrivelistDrive, + } as unknown) as constraints.DrivelistDrive, ({ device: drivePaths[1], description: 'My Other Drive', @@ -1260,7 +1229,7 @@ describe('Shared: DriveConstraints', function () { mountpoints: [], isSystem: false, isReadOnly: true, - } as unknown) as DrivelistDrive, + } as unknown) as constraints.DrivelistDrive, ({ device: drivePaths[2], description: 'My Drive', @@ -1269,7 +1238,7 @@ describe('Shared: DriveConstraints', function () { mountpoints: [], isSystem: false, isReadOnly: false, - } as unknown) as DrivelistDrive, + } as unknown) as constraints.DrivelistDrive, ({ device: drivePaths[3], description: 'My Drive', @@ -1278,16 +1247,16 @@ describe('Shared: DriveConstraints', function () { mountpoints: [], isSystem: true, isReadOnly: false, - } as unknown) as DrivelistDrive, + } as unknown) as constraints.DrivelistDrive, ({ device: drivePaths[4], description: 'My Drive', - size: 64000000001, + size: 128000000001, displayName: drivePaths[4], mountpoints: [], isSystem: false, isReadOnly: false, - } as unknown) as DrivelistDrive, + } as unknown) as constraints.DrivelistDrive, ({ device: drivePaths[5], description: 'My Drive', @@ -1296,7 +1265,7 @@ describe('Shared: DriveConstraints', function () { mountpoints: [], isSystem: false, isReadOnly: false, - } as unknown) as DrivelistDrive, + } as unknown) as constraints.DrivelistDrive, ({ device: drivePaths[6], description: 'My Drive', @@ -1305,11 +1274,14 @@ describe('Shared: DriveConstraints', function () { mountpoints: [], isSystem: false, isReadOnly: false, - } as unknown) as DrivelistDrive, + } as unknown) as constraints.DrivelistDrive, ]; - const image = { + const image: SourceMetadata = { + description: 'rpi.img', + displayName: 'rpi.img', path: path.join(__dirname, 'rpi.img'), + SourceType: sourceDestination.File, // @ts-ignore size: drives[2].size + 1, isSizeEstimated: false, @@ -1362,7 +1334,7 @@ describe('Shared: DriveConstraints', function () { ), ).to.deep.equal([ { - message: 'Insufficient space, additional 1 B required', + message: 'Too small', type: 2, }, ]); @@ -1404,7 +1376,7 @@ describe('Shared: DriveConstraints', function () { ), ).to.deep.equal([ { - message: 'Not Recommended', + message: 'Not recommended', type: 1, }, ]); @@ -1425,7 +1397,7 @@ describe('Shared: DriveConstraints', function () { type: 2, }, { - message: 'Insufficient space, additional 1 B required', + message: 'Too small', type: 2, }, { @@ -1437,157 +1409,11 @@ describe('Shared: DriveConstraints', function () { type: 1, }, { - message: 'Not Recommended', + message: 'Not recommended', type: 1, }, ]); }); }); }); - - describe('.hasListDriveImageCompatibilityStatus()', function () { - const drivePaths = - process.platform === 'win32' - ? ['E:\\', 'F:\\', 'G:\\', 'H:\\', 'J:\\', 'K:\\'] - : [ - '/dev/disk1', - '/dev/disk2', - '/dev/disk3', - '/dev/disk4', - '/dev/disk5', - '/dev/disk6', - ]; - const drives = [ - ({ - device: drivePaths[0], - description: 'My Drive', - size: 123456789, - displayName: drivePaths[0], - mountpoints: [{ path: __dirname }], - isSystem: false, - isReadOnly: false, - } as unknown) as DrivelistDrive, - ({ - device: drivePaths[1], - description: 'My Other Drive', - size: 123456789, - displayName: drivePaths[1], - mountpoints: [], - isSystem: false, - isReadOnly: true, - } as unknown) as DrivelistDrive, - ({ - device: drivePaths[2], - description: 'My Drive', - size: 1234567, - displayName: drivePaths[2], - mountpoints: [], - isSystem: false, - isReadOnly: false, - } as unknown) as DrivelistDrive, - ({ - device: drivePaths[3], - description: 'My Drive', - size: 123456789, - displayName: drivePaths[3], - mountpoints: [], - isSystem: true, - isReadOnly: false, - } as unknown) as DrivelistDrive, - ({ - device: drivePaths[4], - description: 'My Drive', - size: 64000000001, - displayName: drivePaths[4], - mountpoints: [], - isSystem: false, - isReadOnly: false, - } as unknown) as DrivelistDrive, - ({ - device: drivePaths[5], - description: 'My Drive', - size: 12345678, - displayName: drivePaths[5], - mountpoints: [], - isSystem: false, - isReadOnly: false, - } as unknown) as DrivelistDrive, - ({ - device: drivePaths[6], - description: 'My Drive', - size: 123456789, - displayName: drivePaths[6], - mountpoints: [], - isSystem: false, - isReadOnly: false, - } as unknown) as DrivelistDrive, - ]; - - const image = { - path: path.join(__dirname, 'rpi.img'), - // @ts-ignore - size: drives[2].size + 1, - isSizeEstimated: false, - // @ts-ignore - recommendedDriveSize: drives[5].size + 1, - }; - - describe('given no drives', function () { - it('should return false', function () { - expect(constraints.hasListDriveImageCompatibilityStatus([], image)).to - .be.false; - }); - }); - - describe('given one drive', function () { - it('should return true given a drive that contains the image', function () { - expect( - constraints.hasListDriveImageCompatibilityStatus([drives[0]], image), - ).to.be.true; - }); - - it('should return true given a drive that is locked', function () { - expect( - constraints.hasListDriveImageCompatibilityStatus([drives[1]], image), - ).to.be.true; - }); - - it('should return true given a drive that is too small for the image', function () { - expect( - constraints.hasListDriveImageCompatibilityStatus([drives[2]], image), - ).to.be.true; - }); - - it('should return true given a drive that is a system drive', function () { - expect( - constraints.hasListDriveImageCompatibilityStatus([drives[3]], image), - ).to.be.true; - }); - - it('should return true given a drive that is large', function () { - expect( - constraints.hasListDriveImageCompatibilityStatus([drives[4]], image), - ).to.be.true; - }); - - it('should return true given a drive that is not recommended', function () { - expect( - constraints.hasListDriveImageCompatibilityStatus([drives[5]], image), - ).to.be.true; - }); - - it('should return false given a drive with no warnings or errors', function () { - expect( - constraints.hasListDriveImageCompatibilityStatus([drives[6]], image), - ).to.be.false; - }); - }); - - describe('given many drives', function () { - it('should return true given some drives with errors or warnings', function () { - expect(constraints.hasListDriveImageCompatibilityStatus(drives, image)) - .to.be.true; - }); - }); - }); }); From 8fa6e618c4d52f4ec5e5c9fc93c74fb301c789c9 Mon Sep 17 00:00:00 2001 From: Lorenzo Alberto Maria Ambrosi Date: Tue, 1 Sep 2020 12:01:21 +0200 Subject: [PATCH 07/12] Use pretty-bytes instead of custom function Change-type: patch Signed-off-by: Lorenzo Alberto Maria Ambrosi --- .../drive-status-warning-modal.tsx | 4 +- .../target-selector-button.tsx | 12 +++--- lib/gui/app/modules/progress-status.ts | 4 +- lib/gui/app/pages/main/MainPage.tsx | 3 +- lib/shared/units.ts | 7 ---- npm-shrinkwrap.json | 2 +- tests/shared/units.spec.ts | 38 ++----------------- 7 files changed, 15 insertions(+), 55 deletions(-) diff --git a/lib/gui/app/components/drive-status-warning-modal/drive-status-warning-modal.tsx b/lib/gui/app/components/drive-status-warning-modal/drive-status-warning-modal.tsx index e310c8da..451a74fb 100644 --- a/lib/gui/app/components/drive-status-warning-modal/drive-status-warning-modal.tsx +++ b/lib/gui/app/components/drive-status-warning-modal/drive-status-warning-modal.tsx @@ -5,7 +5,7 @@ import { Badge, Flex, Txt, ModalProps } from 'rendition'; import { Modal, ScrollableFlex } from '../../styled-components'; import { middleEllipsis } from '../../utils/middle-ellipsis'; -import { bytesToClosestUnit } from '../../../../shared/units'; +import * as prettyBytes from 'pretty-bytes'; import { DriveWithWarnings } from '../../pages/main/Flash'; const DriveStatusWarningModal = ({ @@ -66,7 +66,7 @@ const DriveStatusWarningModal = ({ <> {middleEllipsis(drive.description, 28)}{' '} - {bytesToClosestUnit(drive.size || 0)}{' '} + {prettyBytes(drive.size || 0)}{' '} {drive.statuses[0].message} {i !== array.length - 1 ?
: null} diff --git a/lib/gui/app/components/target-selector/target-selector-button.tsx b/lib/gui/app/components/target-selector/target-selector-button.tsx index 00ea5b1f..4a05cea4 100644 --- a/lib/gui/app/components/target-selector/target-selector-button.tsx +++ b/lib/gui/app/components/target-selector/target-selector-button.tsx @@ -23,7 +23,7 @@ import { DriveStatus, } from '../../../../shared/drive-constraints'; import { compatibility, warning } from '../../../../shared/messages'; -import { bytesToClosestUnit } from '../../../../shared/units'; +import * as prettyBytes from 'pretty-bytes'; import { getSelectedDrives } from '../../models/selection-state'; import { ChangeButton, @@ -96,7 +96,7 @@ export function TargetSelectorButton(props: TargetSelectorProps) { Change )} - {bytesToClosestUnit(target.size)} + {prettyBytes(target.size)} ); } @@ -110,16 +110,16 @@ export function TargetSelectorButton(props: TargetSelectorProps) { targetsTemplate.push( {warnings.length && ( )} {middleEllipsis(target.description, 14)} - {bytesToClosestUnit(target.size)} + {prettyBytes(target.size)} , ); } diff --git a/lib/gui/app/modules/progress-status.ts b/lib/gui/app/modules/progress-status.ts index 950ac463..6c48b2c2 100644 --- a/lib/gui/app/modules/progress-status.ts +++ b/lib/gui/app/modules/progress-status.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import { bytesToClosestUnit } from '../../../shared/units'; +import * as prettyBytes from 'pretty-bytes'; export interface FlashState { active: number; @@ -51,7 +51,7 @@ export function fromFlashState({ } else { return { status: 'Flashing...', - position: `${position ? bytesToClosestUnit(position) : ''}`, + position: `${position ? prettyBytes(position) : ''}`, }; } } else if (type === 'verifying') { diff --git a/lib/gui/app/pages/main/MainPage.tsx b/lib/gui/app/pages/main/MainPage.tsx index 8deca62a..d23a6874 100644 --- a/lib/gui/app/pages/main/MainPage.tsx +++ b/lib/gui/app/pages/main/MainPage.tsx @@ -18,6 +18,7 @@ import CogSvg from '@fortawesome/fontawesome-free/svgs/solid/cog.svg'; import QuestionCircleSvg from '@fortawesome/fontawesome-free/svgs/solid/question-circle.svg'; import * as path from 'path'; +import * as prettyBytes from 'pretty-bytes'; import * as React from 'react'; import { Flex } from 'rendition'; import styled from 'styled-components'; @@ -40,8 +41,6 @@ import { ThemedProvider, } from '../../styled-components'; -import { bytesToClosestUnit } from '../../../../shared/units'; - import { TargetSelector, getDriveListLabel, diff --git a/lib/shared/units.ts b/lib/shared/units.ts index daae6707..ebf31a65 100644 --- a/lib/shared/units.ts +++ b/lib/shared/units.ts @@ -14,15 +14,8 @@ * limitations under the License. */ -import * as _ from 'lodash'; -import * as prettyBytes from 'pretty-bytes'; - const MEGABYTE_TO_BYTE_RATIO = 1000000; export function bytesToMegabytes(bytes: number): number { return bytes / MEGABYTE_TO_BYTE_RATIO; } - -export function bytesToClosestUnit(bytes: number): string { - return prettyBytes(bytes); -} diff --git a/npm-shrinkwrap.json b/npm-shrinkwrap.json index fdb297d4..433cc4a6 100644 --- a/npm-shrinkwrap.json +++ b/npm-shrinkwrap.json @@ -16775,4 +16775,4 @@ "dev": true } } -} +} \ No newline at end of file diff --git a/tests/shared/units.spec.ts b/tests/shared/units.spec.ts index ccf4b665..071b020e 100644 --- a/tests/shared/units.spec.ts +++ b/tests/shared/units.spec.ts @@ -15,45 +15,13 @@ */ import { expect } from 'chai'; -import * as units from '../../lib/shared/units'; +import { bytesToMegabytes } from '../../lib/shared/units'; describe('Shared: Units', function () { - describe('.bytesToClosestUnit()', function () { - it('should convert bytes to terabytes', function () { - expect(units.bytesToClosestUnit(1000000000000)).to.equal('1 TB'); - expect(units.bytesToClosestUnit(2987801405440)).to.equal('2.99 TB'); - expect(units.bytesToClosestUnit(999900000000000)).to.equal('1000 TB'); - }); - - it('should convert bytes to gigabytes', function () { - expect(units.bytesToClosestUnit(1000000000)).to.equal('1 GB'); - expect(units.bytesToClosestUnit(7801405440)).to.equal('7.8 GB'); - expect(units.bytesToClosestUnit(999900000000)).to.equal('1000 GB'); - }); - - it('should convert bytes to megabytes', function () { - expect(units.bytesToClosestUnit(1000000)).to.equal('1 MB'); - expect(units.bytesToClosestUnit(801405440)).to.equal('801 MB'); - expect(units.bytesToClosestUnit(999900000)).to.equal('1000 MB'); - }); - - it('should convert bytes to kilobytes', function () { - expect(units.bytesToClosestUnit(1000)).to.equal('1 kB'); - expect(units.bytesToClosestUnit(5440)).to.equal('5.44 kB'); - expect(units.bytesToClosestUnit(999900)).to.equal('1000 kB'); - }); - - it('should keep bytes as bytes', function () { - expect(units.bytesToClosestUnit(1)).to.equal('1 B'); - expect(units.bytesToClosestUnit(8)).to.equal('8 B'); - expect(units.bytesToClosestUnit(999)).to.equal('999 B'); - }); - }); - describe('.bytesToMegabytes()', function () { it('should convert bytes to megabytes', function () { - expect(units.bytesToMegabytes(1.2e7)).to.equal(12); - expect(units.bytesToMegabytes(332000)).to.equal(0.332); + expect(bytesToMegabytes(1.2e7)).to.equal(12); + expect(bytesToMegabytes(332000)).to.equal(0.332); }); }); }); From 14a89b3b8a25ae82e153e56bc97fcad983e1bbf4 Mon Sep 17 00:00:00 2001 From: Lorenzo Alberto Maria Ambrosi Date: Wed, 2 Sep 2020 17:39:40 +0200 Subject: [PATCH 08/12] Remove lodash from selection-state.ts Change-type: patch Signed-off-by: Lorenzo Alberto Maria Ambrosi --- lib/gui/app/models/selection-state.ts | 33 ++++++++++++--------------- 1 file changed, 14 insertions(+), 19 deletions(-) diff --git a/lib/gui/app/models/selection-state.ts b/lib/gui/app/models/selection-state.ts index 06244e05..a7de51aa 100644 --- a/lib/gui/app/models/selection-state.ts +++ b/lib/gui/app/models/selection-state.ts @@ -14,7 +14,6 @@ * limitations under the License. */ -import * as _ from 'lodash'; import { SourceMetadata } from '../components/source-selector/source-selector'; import * as availableDrives from './available-drives'; @@ -60,48 +59,44 @@ export function getSelectedDevices(): string[] { */ export function getSelectedDrives(): any[] { const drives = availableDrives.getDrives(); - return _.map(getSelectedDevices(), (device) => { - return _.find(drives, { device }); + return getSelectedDevices().map((device) => { + return drives.find((drive) => drive.device === device); }); } /** * @summary Get the selected image */ -export function getImage(): SourceMetadata { - return _.get(store.getState().toJS(), ['selection', 'image']); +export function getImage(): SourceMetadata | undefined { + return store.getState().toJS().selection.image; } export function getImagePath(): string { - return _.get(store.getState().toJS(), ['selection', 'image', 'path']); + return store.getState().toJS().selection.image?.path; } export function getImageSize(): number { - return _.get(store.getState().toJS(), ['selection', 'image', 'size']); + return store.getState().toJS().selection.image?.size; } export function getImageUrl(): string { - return _.get(store.getState().toJS(), ['selection', 'image', 'url']); + return store.getState().toJS().selection.image?.url; } export function getImageName(): string { - return _.get(store.getState().toJS(), ['selection', 'image', 'name']); + return store.getState().toJS().selection.image?.name; } export function getImageLogo(): string { - return _.get(store.getState().toJS(), ['selection', 'image', 'logo']); + return store.getState().toJS().selection.image?.logo; } export function getImageSupportUrl(): string { - return _.get(store.getState().toJS(), ['selection', 'image', 'supportUrl']); + return store.getState().toJS().selection.image?.supportUrl; } export function getImageRecommendedDriveSize(): number { - return _.get(store.getState().toJS(), [ - 'selection', - 'image', - 'recommendedDriveSize', - ]); + return store.getState().toJS().selection.image?.recommendedDriveSize; } /** @@ -115,7 +110,7 @@ export function hasDrive(): boolean { * @summary Check if there is a selected image */ export function hasImage(): boolean { - return !_.isEmpty(getImage()); + return getImage() !== undefined; } /** @@ -136,7 +131,7 @@ export function deselectImage() { } export function deselectAllDrives() { - _.each(getSelectedDevices(), deselectDrive); + getSelectedDevices().forEach(deselectDrive); } /** @@ -156,5 +151,5 @@ export function isDriveSelected(driveDevice: string) { } const selectedDriveDevices = getSelectedDevices(); - return _.includes(selectedDriveDevices, driveDevice); + return selectedDriveDevices.includes(driveDevice); } From f9d79521a11f09fdd2a31ccba9de096a11b292eb Mon Sep 17 00:00:00 2001 From: Lorenzo Alberto Maria Ambrosi Date: Wed, 2 Sep 2020 17:40:11 +0200 Subject: [PATCH 09/12] Fix tests not running Change-type: patch Signed-off-by: Lorenzo Alberto Maria Ambrosi --- lib/shared/drive-constraints.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/shared/drive-constraints.ts b/lib/shared/drive-constraints.ts index c75bd719..0e92a615 100644 --- a/lib/shared/drive-constraints.ts +++ b/lib/shared/drive-constraints.ts @@ -266,6 +266,7 @@ export function getListDriveImageCompatibilityStatuses( drives: DrivelistDrive[], image: SourceMetadata, ) { + // @ts-ignore return drives.flatMap((drive) => { return getDriveImageCompatibilityStatuses(drive, image); }); From 3e45691d0b207eb476df38a1b2250ffe4fa91fa7 Mon Sep 17 00:00:00 2001 From: Alexis Svinartchouk Date: Tue, 1 Sep 2020 16:40:34 +0200 Subject: [PATCH 10/12] Re-enable ext partitions trimming on 32 bit Windows Changelog-entry: Re-enable ext partitions trimming on 32 bit Windows Change-type: patch --- npm-shrinkwrap.json | 14 +++++++------- package.json | 2 +- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/npm-shrinkwrap.json b/npm-shrinkwrap.json index 433cc4a6..ce8d16f3 100644 --- a/npm-shrinkwrap.json +++ b/npm-shrinkwrap.json @@ -6683,15 +6683,15 @@ "dev": true }, "etcher-sdk": { - "version": "4.1.29", - "resolved": "https://registry.npmjs.org/etcher-sdk/-/etcher-sdk-4.1.29.tgz", - "integrity": "sha512-dMzrCFgd6WHe/tqsFapHKjTXA32YL/J+p/RnJztQeMfV3b0cQiUINp6ZX4cU6lfbL8cpRVp4y61Qo5vhMbycZw==", + "version": "4.1.30", + "resolved": "https://registry.npmjs.org/etcher-sdk/-/etcher-sdk-4.1.30.tgz", + "integrity": "sha512-HINIm5b/nOnY4v5XGRQFYQsHOSHGM/iukMm56WblsKEQPRBjZzZfHUzsyZcbsclFhw//x+iPbkDKUbf5uBpk1Q==", "dev": true, "requires": { "@balena/udif": "^1.1.0", "@ronomon/direct-io": "^3.0.1", "axios": "^0.19.2", - "balena-image-fs": "^7.0.0-remove-bluebird-9150c6c0fee21e33beef0ddaeea56ad1ce175c96", + "balena-image-fs": "^7.0.1", "blockmap": "^4.0.1", "check-disk-space": "^2.1.0", "cyclic-32": "^1.1.0", @@ -6871,9 +6871,9 @@ } }, "ext2fs": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/ext2fs/-/ext2fs-2.0.1.tgz", - "integrity": "sha512-ZhnpAINB0+Lsgt5jwyAMQKe/w9L1WaNiERyGvXlO7sd9doGaxrVotyX3+ZPbyNMgPb/7wJ0zbeRp+DLAzZQdug==", + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/ext2fs/-/ext2fs-2.0.4.tgz", + "integrity": "sha512-7ILtkKb6j9L+nR1qO4zCiy6aZulzKu7dO82na+qXwc6KEoEr23u/u476/thebbPcvYJMv71I7FebJv8P4MNjHw==", "dev": true, "requires": { "bindings": "^1.3.0", diff --git a/package.json b/package.json index c04f63c7..61eb5749 100644 --- a/package.json +++ b/package.json @@ -77,7 +77,7 @@ "electron-notarize": "^1.0.0", "electron-rebuild": "^1.11.0", "electron-updater": "^4.3.2", - "etcher-sdk": "^4.1.29", + "etcher-sdk": "^4.1.30", "file-loader": "^6.0.0", "husky": "^4.2.5", "immutable": "^3.8.1", From eeab35163658c982f9ec35f37b40649d5f99fad6 Mon Sep 17 00:00:00 2001 From: Lorenzo Alberto Maria Ambrosi Date: Wed, 2 Sep 2020 19:00:07 +0200 Subject: [PATCH 11/12] Fix tests hanging on array.flatMap Change-type: patch Signed-off-by: Lorenzo Alberto Maria Ambrosi --- lib/shared/drive-constraints.ts | 1 - tsconfig.json | 2 ++ 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/lib/shared/drive-constraints.ts b/lib/shared/drive-constraints.ts index 0e92a615..c75bd719 100644 --- a/lib/shared/drive-constraints.ts +++ b/lib/shared/drive-constraints.ts @@ -266,7 +266,6 @@ export function getListDriveImageCompatibilityStatuses( drives: DrivelistDrive[], image: SourceMetadata, ) { - // @ts-ignore return drives.flatMap((drive) => { return getDriveImageCompatibilityStatuses(drive, image); }); diff --git a/tsconfig.json b/tsconfig.json index 9cdd39ef..aefede61 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -4,6 +4,8 @@ "noUnusedLocals": true, "noUnusedParameters": true, "resolveJsonModule": true, + "target": "es2019", + "moduleResolution": "node", "jsx": "react", "typeRoots": ["./node_modules/@types", "./typings"] } From b76366a514edd494188cfdc6eccbd2a1d2c49c61 Mon Sep 17 00:00:00 2001 From: Lorenzo Alberto Maria Ambrosi Date: Thu, 3 Sep 2020 15:46:18 +0200 Subject: [PATCH 12/12] Add more typings & refactor code accordingly Change-type: patch Signed-off-by: Lorenzo Alberto Maria Ambrosi --- lib/gui/app/app.ts | 10 +- .../drive-selector/drive-selector.tsx | 4 +- .../drive-status-warning-modal.tsx | 2 +- .../reduced-flashing-infos.tsx | 9 +- .../source-selector/source-selector.tsx | 11 +- lib/gui/app/components/svg-icon/svg-icon.tsx | 5 +- .../target-selector-button.tsx | 16 +- lib/gui/app/models/available-drives.ts | 3 +- lib/gui/app/models/selection-state.ts | 41 ++-- lib/gui/app/pages/main/Flash.tsx | 18 +- lib/gui/app/pages/main/MainPage.tsx | 8 +- lib/shared/messages.ts | 18 +- tests/gui/models/available-drives.spec.ts | 4 + tests/gui/models/selection-state.spec.ts | 224 +++++------------- 14 files changed, 140 insertions(+), 233 deletions(-) diff --git a/lib/gui/app/app.ts b/lib/gui/app/app.ts index 6443d943..ab4325f8 100644 --- a/lib/gui/app/app.ts +++ b/lib/gui/app/app.ts @@ -23,7 +23,11 @@ import * as ReactDOM from 'react-dom'; import { v4 as uuidV4 } from 'uuid'; import * as packageJSON from '../../../package.json'; -import { isDriveValid, isSourceDrive } from '../../shared/drive-constraints'; +import { + DrivelistDrive, + isDriveValid, + isSourceDrive, +} from '../../shared/drive-constraints'; import * as EXIT_CODES from '../../shared/exit-codes'; import * as messages from '../../shared/messages'; import * as availableDrives from './models/available-drives'; @@ -231,12 +235,12 @@ function prepareDrive(drive: Drive) { } } -function setDrives(drives: _.Dictionary) { +function setDrives(drives: _.Dictionary) { availableDrives.setDrives(_.values(drives)); } function getDrives() { - return _.keyBy(availableDrives.getDrives() || [], 'device'); + return _.keyBy(availableDrives.getDrives(), 'device'); } async function addDrive(drive: Drive) { diff --git a/lib/gui/app/components/drive-selector/drive-selector.tsx b/lib/gui/app/components/drive-selector/drive-selector.tsx index 290db14c..8bd3daef 100644 --- a/lib/gui/app/components/drive-selector/drive-selector.tsx +++ b/lib/gui/app/components/drive-selector/drive-selector.tsx @@ -289,8 +289,8 @@ export class DriveSelector extends React.Component< { field: 'description', key: 'extra', - // Space as empty string would use the field name as label - label: , + // We use an empty React fragment otherwise it uses the field name as label + label: <>, render: (_description: string, drive: Drive) => { if (isUsbbootDrive(drive)) { return this.renderProgress(drive.progress); diff --git a/lib/gui/app/components/drive-status-warning-modal/drive-status-warning-modal.tsx b/lib/gui/app/components/drive-status-warning-modal/drive-status-warning-modal.tsx index 451a74fb..4000917e 100644 --- a/lib/gui/app/components/drive-status-warning-modal/drive-status-warning-modal.tsx +++ b/lib/gui/app/components/drive-status-warning-modal/drive-status-warning-modal.tsx @@ -66,7 +66,7 @@ const DriveStatusWarningModal = ({ <> {middleEllipsis(drive.description, 28)}{' '} - {prettyBytes(drive.size || 0)}{' '} + {drive.size && prettyBytes(drive.size) + ' '} {drive.statuses[0].message} {i !== array.length - 1 ?
: null} diff --git a/lib/gui/app/components/reduced-flashing-infos/reduced-flashing-infos.tsx b/lib/gui/app/components/reduced-flashing-infos/reduced-flashing-infos.tsx index 527f45fc..539c3b2f 100644 --- a/lib/gui/app/components/reduced-flashing-infos/reduced-flashing-infos.tsx +++ b/lib/gui/app/components/reduced-flashing-infos/reduced-flashing-infos.tsx @@ -23,8 +23,8 @@ import { SVGIcon } from '../svg-icon/svg-icon'; import { middleEllipsis } from '../../utils/middle-ellipsis'; interface ReducedFlashingInfosProps { - imageLogo: string; - imageName: string; + imageLogo?: string; + imageName?: string; imageSize: string; driveTitle: string; driveLabel: string; @@ -40,6 +40,7 @@ export class ReducedFlashingInfos extends React.Component< } public render() { + const { imageName = '' } = this.props; return ( - {middleEllipsis(this.props.imageName, 16)} + {middleEllipsis(imageName, 16)} {this.props.imageSize} diff --git a/lib/gui/app/components/source-selector/source-selector.tsx b/lib/gui/app/components/source-selector/source-selector.tsx index c07fd83c..2e8dc3d6 100644 --- a/lib/gui/app/components/source-selector/source-selector.tsx +++ b/lib/gui/app/components/source-selector/source-selector.tsx @@ -254,6 +254,7 @@ export interface SourceMetadata extends sourceDestination.Metadata { SourceType: Source; drive?: DrivelistDrive; extension?: string; + archiveExtension?: string; } interface SourceSelectorProps { @@ -262,8 +263,8 @@ interface SourceSelectorProps { interface SourceSelectorState { hasImage: boolean; - imageName: string; - imageSize: number; + imageName?: string; + imageSize?: number; warning: { message: string; title: string | null } | null; showImageDetails: boolean; showURLSelector: boolean; @@ -543,7 +544,7 @@ export class SourceSelector extends React.Component< const imagePath = image.path || image.displayName || ''; const imageBasename = path.basename(imagePath); const imageName = image.name || ''; - const imageSize = image.size || 0; + const imageSize = image.size; const imageLogo = image.logo || ''; return ( @@ -585,7 +586,9 @@ export class SourceSelector extends React.Component< Remove )} - {prettyBytes(imageSize)} + {!_.isNil(imageSize) && ( + {prettyBytes(imageSize)} + )} ) : ( <> diff --git a/lib/gui/app/components/svg-icon/svg-icon.tsx b/lib/gui/app/components/svg-icon/svg-icon.tsx index bcf2d777..3059fe8e 100644 --- a/lib/gui/app/components/svg-icon/svg-icon.tsx +++ b/lib/gui/app/components/svg-icon/svg-icon.tsx @@ -37,8 +37,9 @@ function tryParseSVGContents(contents?: string): string | undefined { } interface SVGIconProps { - // List of embedded SVG contents to be tried in succession if any fails - contents: string; + // Optional string representing the SVG contents to be tried + contents?: string; + // Fallback SVG element to show if `contents` is invalid/undefined fallback: React.FunctionComponent>; // SVG image width unit width?: string; diff --git a/lib/gui/app/components/target-selector/target-selector-button.tsx b/lib/gui/app/components/target-selector/target-selector-button.tsx index 4a05cea4..1b529b45 100644 --- a/lib/gui/app/components/target-selector/target-selector-button.tsx +++ b/lib/gui/app/components/target-selector/target-selector-button.tsx @@ -96,7 +96,9 @@ export function TargetSelectorButton(props: TargetSelectorProps) { Change )} - {prettyBytes(target.size)} + {target.size != null && ( + {prettyBytes(target.size)} + )} ); } @@ -110,16 +112,16 @@ export function TargetSelectorButton(props: TargetSelectorProps) { targetsTemplate.push( - {warnings.length && ( + {warnings.length > 0 ? ( - )} + ) : null} {middleEllipsis(target.description, 14)} - {prettyBytes(target.size)} + {target.size != null && {prettyBytes(target.size)}} , ); } diff --git a/lib/gui/app/models/available-drives.ts b/lib/gui/app/models/available-drives.ts index 7acc4a55..0bff74fb 100644 --- a/lib/gui/app/models/available-drives.ts +++ b/lib/gui/app/models/available-drives.ts @@ -14,6 +14,7 @@ * limitations under the License. */ +import { DrivelistDrive } from '../../../shared/drive-constraints'; import { Actions, store } from './store'; export function hasAvailableDrives() { @@ -27,6 +28,6 @@ export function setDrives(drives: any[]) { }); } -export function getDrives(): any[] { +export function getDrives(): DrivelistDrive[] { return store.getState().toJS().availableDrives; } diff --git a/lib/gui/app/models/selection-state.ts b/lib/gui/app/models/selection-state.ts index a7de51aa..959cf828 100644 --- a/lib/gui/app/models/selection-state.ts +++ b/lib/gui/app/models/selection-state.ts @@ -1,3 +1,4 @@ +import { DrivelistDrive } from '../../../shared/drive-constraints'; /* * Copyright 2016 balena.io * @@ -40,7 +41,7 @@ export function toggleDrive(driveDevice: string) { } } -export function selectSource(source: any) { +export function selectSource(source: SourceMetadata) { store.dispatch({ type: Actions.SELECT_SOURCE, data: source, @@ -57,11 +58,11 @@ export function getSelectedDevices(): string[] { /** * @summary Get all selected drive objects */ -export function getSelectedDrives(): any[] { - const drives = availableDrives.getDrives(); - return getSelectedDevices().map((device) => { - return drives.find((drive) => drive.device === device); - }); +export function getSelectedDrives(): DrivelistDrive[] { + const selectedDevices = getSelectedDevices(); + return availableDrives + .getDrives() + .filter((drive) => selectedDevices.includes(drive.device)); } /** @@ -71,32 +72,24 @@ export function getImage(): SourceMetadata | undefined { return store.getState().toJS().selection.image; } -export function getImagePath(): string { - return store.getState().toJS().selection.image?.path; +export function getImagePath() { + return getImage()?.path; } -export function getImageSize(): number { - return store.getState().toJS().selection.image?.size; +export function getImageSize() { + return getImage()?.size; } -export function getImageUrl(): string { - return store.getState().toJS().selection.image?.url; +export function getImageName() { + return getImage()?.name; } -export function getImageName(): string { - return store.getState().toJS().selection.image?.name; +export function getImageLogo() { + return getImage()?.logo; } -export function getImageLogo(): string { - return store.getState().toJS().selection.image?.logo; -} - -export function getImageSupportUrl(): string { - return store.getState().toJS().selection.image?.supportUrl; -} - -export function getImageRecommendedDriveSize(): number { - return store.getState().toJS().selection.image?.recommendedDriveSize; +export function getImageSupportUrl() { + return getImage()?.supportUrl; } /** diff --git a/lib/gui/app/pages/main/Flash.tsx b/lib/gui/app/pages/main/Flash.tsx index 62ed0637..57c4b4f3 100644 --- a/lib/gui/app/pages/main/Flash.tsx +++ b/lib/gui/app/pages/main/Flash.tsx @@ -198,18 +198,12 @@ export class FlashStep extends React.PureComponent< } private async tryFlash() { - const devices = selection.getSelectedDevices(); - const drives = availableDrives - .getDrives() - .filter((drive: { device: string }) => { - return devices.includes(drive.device); - }) - .map((drive) => { - return { - ...drive, - statuses: constraints.getDriveImageCompatibilityStatuses(drive), - }; - }); + const drives = selection.getSelectedDrives().map((drive) => { + return { + ...drive, + statuses: constraints.getDriveImageCompatibilityStatuses(drive), + }; + }); if (drives.length === 0 || this.props.isFlashing) { return; } diff --git a/lib/gui/app/pages/main/MainPage.tsx b/lib/gui/app/pages/main/MainPage.tsx index d23a6874..47e2c9da 100644 --- a/lib/gui/app/pages/main/MainPage.tsx +++ b/lib/gui/app/pages/main/MainPage.tsx @@ -103,9 +103,9 @@ interface MainPageStateFromStore { isFlashing: boolean; hasImage: boolean; hasDrive: boolean; - imageLogo: string; - imageSize: number; - imageName: string; + imageLogo?: string; + imageSize?: number; + imageName?: string; driveTitle: string; driveLabel: string; } @@ -272,7 +272,7 @@ export class MainPage extends React.Component< imageName={this.state.imageName} imageSize={ typeof this.state.imageSize === 'number' - ? (prettyBytes(this.state.imageSize) as string) + ? prettyBytes(this.state.imageSize) : '' } driveTitle={this.state.driveTitle} diff --git a/lib/shared/messages.ts b/lib/shared/messages.ts index b3cd838b..9bdd3372 100644 --- a/lib/shared/messages.ts +++ b/lib/shared/messages.ts @@ -15,6 +15,7 @@ */ import { Dictionary } from 'lodash'; +import { outdent } from 'outdent'; import * as prettyBytes from 'pretty-bytes'; export const progress: Dictionary<(quantity: number) => string> = { @@ -84,10 +85,10 @@ export const warning = { image: { recommendedDriveSize: number }, drive: { device: string; size: number }, ) => { - return [ - `This image recommends a ${prettyBytes(image.recommendedDriveSize)}`, - `drive, however ${drive.device} is only ${prettyBytes(drive.size)}.`, - ].join(' '); + return outdent({ newline: ' ' })` + This image recommends a ${prettyBytes(image.recommendedDriveSize)} + drive, however ${drive.device} is only ${prettyBytes(drive.size)}. + `; }, exitWhileFlashing: () => { @@ -150,10 +151,11 @@ export const error = { }, openSource: (sourceName: string, errorMessage: string) => { - return [ - `Something went wrong while opening ${sourceName}\n\n`, - `Error: ${errorMessage}`, - ].join(''); + return outdent` + Something went wrong while opening ${sourceName} + + Error: ${errorMessage} + `; }, flashFailure: ( diff --git a/tests/gui/models/available-drives.spec.ts b/tests/gui/models/available-drives.spec.ts index 126a4640..81b9933e 100644 --- a/tests/gui/models/available-drives.spec.ts +++ b/tests/gui/models/available-drives.spec.ts @@ -15,6 +15,7 @@ */ import { expect } from 'chai'; +import { File } from 'etcher-sdk/build/source-destination'; import * as path from 'path'; import * as availableDrives from '../../../lib/gui/app/models/available-drives'; @@ -158,10 +159,13 @@ describe('Model: availableDrives', function () { selectionState.clear(); selectionState.selectSource({ + description: this.imagePath.split('/').pop(), + displayName: this.imagePath, path: this.imagePath, extension: 'img', size: 999999999, isSizeEstimated: false, + SourceType: File, recommendedDriveSize: 2000000000, }); }); diff --git a/tests/gui/models/selection-state.spec.ts b/tests/gui/models/selection-state.spec.ts index 234dde8b..3e28f8c4 100644 --- a/tests/gui/models/selection-state.spec.ts +++ b/tests/gui/models/selection-state.spec.ts @@ -15,11 +15,13 @@ */ import { expect } from 'chai'; -import * as _ from 'lodash'; +import { File } from 'etcher-sdk/build/source-destination'; import * as path from 'path'; +import { SourceMetadata } from '../../../lib/gui/app/components/source-selector/source-selector'; import * as availableDrives from '../../../lib/gui/app/models/available-drives'; import * as selectionState from '../../../lib/gui/app/models/selection-state'; +import { DrivelistDrive } from '../../../lib/shared/drive-constraints'; describe('Model: selectionState', function () { describe('given a clean state', function () { @@ -39,10 +41,6 @@ describe('Model: selectionState', function () { expect(selectionState.getImageSize()).to.be.undefined; }); - it('getImageUrl() should return undefined', function () { - expect(selectionState.getImageUrl()).to.be.undefined; - }); - it('getImageName() should return undefined', function () { expect(selectionState.getImageName()).to.be.undefined; }); @@ -55,10 +53,6 @@ describe('Model: selectionState', function () { expect(selectionState.getImageSupportUrl()).to.be.undefined; }); - it('getImageRecommendedDriveSize() should return undefined', function () { - expect(selectionState.getImageRecommendedDriveSize()).to.be.undefined; - }); - it('hasDrive() should return false', function () { const hasDrive = selectionState.hasDrive(); expect(hasDrive).to.be.false; @@ -138,10 +132,10 @@ describe('Model: selectionState', function () { it('should queue the drive', function () { selectionState.selectDrive('/dev/disk5'); const drives = selectionState.getSelectedDevices(); - const lastDriveDevice = _.last(drives); - const lastDrive = _.find(availableDrives.getDrives(), { - device: lastDriveDevice, - }); + const lastDriveDevice = drives.pop(); + const lastDrive = availableDrives + .getDrives() + .find((drive) => drive.device === lastDriveDevice); expect(lastDrive).to.deep.equal({ device: '/dev/disk5', name: 'USB Drive', @@ -214,7 +208,7 @@ describe('Model: selectionState', function () { it('should be able to add more drives', function () { selectionState.selectDrive(this.drives[2].device); expect(selectionState.getSelectedDevices()).to.deep.equal( - _.map(this.drives, 'device'), + this.drives.map((drive: DrivelistDrive) => drive.device), ); }); @@ -234,13 +228,13 @@ describe('Model: selectionState', function () { system: true, }; - const newDrives = [..._.initial(this.drives), systemDrive]; + const newDrives = [...this.drives.slice(0, -1), systemDrive]; availableDrives.setDrives(newDrives); selectionState.selectDrive(systemDrive.device); availableDrives.setDrives(newDrives); expect(selectionState.getSelectedDevices()).to.deep.equal( - _.map(newDrives, 'device'), + newDrives.map((drive: DrivelistDrive) => drive.device), ); }); @@ -271,6 +265,12 @@ describe('Model: selectionState', function () { describe('.getSelectedDrives()', function () { it('should return the selected drives', function () { expect(selectionState.getSelectedDrives()).to.deep.equal([ + { + device: '/dev/disk2', + name: 'USB Drive 2', + size: 999999999, + isReadOnly: false, + }, { device: '/dev/sdb', description: 'DataTraveler 2.0', @@ -280,12 +280,6 @@ describe('Model: selectionState', function () { system: false, isReadOnly: false, }, - { - device: '/dev/disk2', - name: 'USB Drive 2', - size: 999999999, - isReadOnly: false, - }, ]); }); }); @@ -399,13 +393,6 @@ describe('Model: selectionState', function () { }); }); - describe('.getImageUrl()', function () { - it('should return the image url', function () { - const imageUrl = selectionState.getImageUrl(); - expect(imageUrl).to.equal('https://www.raspbian.org'); - }); - }); - describe('.getImageName()', function () { it('should return the image name', function () { const imageName = selectionState.getImageName(); @@ -429,13 +416,6 @@ describe('Model: selectionState', function () { }); }); - describe('.getImageRecommendedDriveSize()', function () { - it('should return the image recommended drive size', function () { - const imageRecommendedDriveSize = selectionState.getImageRecommendedDriveSize(); - expect(imageRecommendedDriveSize).to.equal(1000000000); - }); - }); - describe('.hasImage()', function () { it('should return true', function () { const hasImage = selectionState.hasImage(); @@ -446,10 +426,13 @@ describe('Model: selectionState', function () { describe('.selectImage()', function () { it('should override the image', function () { selectionState.selectSource({ + description: 'bar.img', + displayName: 'bar.img', path: 'bar.img', extension: 'img', size: 999999999, isSizeEstimated: false, + SourceType: File, }); const imagePath = selectionState.getImagePath(); @@ -475,13 +458,19 @@ describe('Model: selectionState', function () { describe('.selectImage()', function () { afterEach(selectionState.clear); + const image: SourceMetadata = { + description: 'foo.img', + displayName: 'foo.img', + path: 'foo.img', + extension: 'img', + size: 999999999, + isSizeEstimated: false, + SourceType: File, + recommendedDriveSize: 2000000000, + }; + it('should be able to set an image', function () { - selectionState.selectSource({ - path: 'foo.img', - extension: 'img', - size: 999999999, - isSizeEstimated: false, - }); + selectionState.selectSource(image); const imagePath = selectionState.getImagePath(); expect(imagePath).to.equal('foo.img'); @@ -491,11 +480,9 @@ describe('Model: selectionState', function () { it('should be able to set an image with an archive extension', function () { selectionState.selectSource({ + ...image, path: 'foo.zip', - extension: 'img', archiveExtension: 'zip', - size: 999999999, - isSizeEstimated: false, }); const imagePath = selectionState.getImagePath(); @@ -504,11 +491,9 @@ describe('Model: selectionState', function () { it('should infer a compressed raw image if the penultimate extension is missing', function () { selectionState.selectSource({ + ...image, path: 'foo.xz', - extension: 'img', archiveExtension: 'xz', - size: 999999999, - isSizeEstimated: false, }); const imagePath = selectionState.getImagePath(); @@ -517,53 +502,19 @@ describe('Model: selectionState', function () { it('should infer a compressed raw image if the penultimate extension is not a file extension', function () { selectionState.selectSource({ + ...image, path: 'something.linux-x86-64.gz', - extension: 'img', archiveExtension: 'gz', - size: 999999999, - isSizeEstimated: false, }); const imagePath = selectionState.getImagePath(); expect(imagePath).to.equal('something.linux-x86-64.gz'); }); - it('should throw if no path', function () { - expect(function () { - selectionState.selectSource({ - extension: 'img', - size: 999999999, - isSizeEstimated: false, - }); - }).to.throw('Missing image fields: path'); - }); - - it('should throw if path is not a string', function () { - expect(function () { - selectionState.selectSource({ - path: 123, - extension: 'img', - size: 999999999, - isSizeEstimated: false, - }); - }).to.throw('Invalid image path: 123'); - }); - - it('should throw if the original size is not a number', function () { - expect(function () { - selectionState.selectSource({ - path: 'foo.img', - extension: 'img', - size: 999999999, - compressedSize: '999999999', - isSizeEstimated: false, - }); - }).to.throw('Invalid image compressed size: 999999999'); - }); - it('should throw if the original size is a float number', function () { expect(function () { selectionState.selectSource({ + ...image, path: 'foo.img', extension: 'img', size: 999999999, @@ -576,33 +527,17 @@ describe('Model: selectionState', function () { it('should throw if the original size is negative', function () { expect(function () { selectionState.selectSource({ - path: 'foo.img', - extension: 'img', - size: 999999999, + ...image, compressedSize: -1, - isSizeEstimated: false, }); }).to.throw('Invalid image compressed size: -1'); }); - it('should throw if the final size is not a number', function () { - expect(function () { - selectionState.selectSource({ - path: 'foo.img', - extension: 'img', - size: '999999999', - isSizeEstimated: false, - }); - }).to.throw('Invalid image size: 999999999'); - }); - it('should throw if the final size is a float number', function () { expect(function () { selectionState.selectSource({ - path: 'foo.img', - extension: 'img', + ...image, size: 999999999.999, - isSizeEstimated: false, }); }).to.throw('Invalid image size: 999999999.999'); }); @@ -610,50 +545,12 @@ describe('Model: selectionState', function () { it('should throw if the final size is negative', function () { expect(function () { selectionState.selectSource({ - path: 'foo.img', - extension: 'img', + ...image, size: -1, - isSizeEstimated: false, }); }).to.throw('Invalid image size: -1'); }); - it("should throw if url is defined but it's not a string", function () { - expect(function () { - selectionState.selectSource({ - path: 'foo.img', - extension: 'img', - size: 999999999, - isSizeEstimated: false, - url: 1234, - }); - }).to.throw('Invalid image url: 1234'); - }); - - it("should throw if name is defined but it's not a string", function () { - expect(function () { - selectionState.selectSource({ - path: 'foo.img', - extension: 'img', - size: 999999999, - isSizeEstimated: false, - name: 1234, - }); - }).to.throw('Invalid image name: 1234'); - }); - - it("should throw if logo is defined but it's not a string", function () { - expect(function () { - selectionState.selectSource({ - path: 'foo.img', - extension: 'img', - size: 999999999, - isSizeEstimated: false, - logo: 1234, - }); - }).to.throw('Invalid image logo: 1234'); - }); - it('should de-select a previously selected not-large-enough drive', function () { availableDrives.setDrives([ { @@ -668,10 +565,8 @@ describe('Model: selectionState', function () { expect(selectionState.hasDrive()).to.be.true; selectionState.selectSource({ - path: 'foo.img', - extension: 'img', + ...image, size: 1234567890, - isSizeEstimated: false, }); expect(selectionState.hasDrive()).to.be.false; @@ -692,10 +587,7 @@ describe('Model: selectionState', function () { expect(selectionState.hasDrive()).to.be.true; selectionState.selectSource({ - path: 'foo.img', - extension: 'img', - size: 999999999, - isSizeEstimated: false, + ...image, recommendedDriveSize: 1500000000, }); @@ -727,10 +619,10 @@ describe('Model: selectionState', function () { expect(selectionState.hasDrive()).to.be.true; selectionState.selectSource({ + ...image, path: imagePath, extension: 'img', size: 999999999, - isSizeEstimated: false, }); expect(selectionState.hasDrive()).to.be.false; @@ -740,6 +632,16 @@ describe('Model: selectionState', function () { }); describe('given a drive and an image', function () { + const image: SourceMetadata = { + description: 'foo.img', + displayName: 'foo.img', + path: 'foo.img', + extension: 'img', + size: 999999999, + SourceType: File, + isSizeEstimated: false, + }; + beforeEach(function () { availableDrives.setDrives([ { @@ -752,12 +654,7 @@ describe('Model: selectionState', function () { selectionState.selectDrive('/dev/disk1'); - selectionState.selectSource({ - path: 'foo.img', - extension: 'img', - size: 999999999, - isSizeEstimated: false, - }); + selectionState.selectSource(image); }); describe('.clear()', function () { @@ -824,6 +721,16 @@ describe('Model: selectionState', function () { }); describe('given several drives', function () { + const image: SourceMetadata = { + description: 'foo.img', + displayName: 'foo.img', + path: 'foo.img', + extension: 'img', + size: 999999999, + SourceType: File, + isSizeEstimated: false, + }; + beforeEach(function () { availableDrives.setDrives([ { @@ -850,12 +757,7 @@ describe('Model: selectionState', function () { selectionState.selectDrive('/dev/disk2'); selectionState.selectDrive('/dev/disk3'); - selectionState.selectSource({ - path: 'foo.img', - extension: 'img', - size: 999999999, - isSizeEstimated: false, - }); + selectionState.selectSource(image); }); describe('.clear()', function () {