Skip to content

Commit

Permalink
push files to container
Browse files Browse the repository at this point in the history
  • Loading branch information
chenyan-dfinity committed Sep 10, 2024
1 parent af7b0b9 commit b7dad2d
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 17 deletions.
50 changes: 36 additions & 14 deletions src/components/Editor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ import {
getActorAliases,
WorkerContext,
WorkplaceDispatchContext,
ContainerContext,
convertNonMotokoFilesToWebContainer,
} from "../contexts/WorkplaceState";
import { compileCandid } from "../build";
import { didToJs } from "../config/actor";
Expand Down Expand Up @@ -99,21 +101,23 @@ export function Editor({
}) {
const worker = useContext(WorkerContext);
const dispatch = useContext(WorkplaceDispatchContext);
const container = useContext(ContainerContext);

const [formatted, setFormatted] = useState(false);

const fileName = state.selectedFile;
const fileExtension = fileName?.split(".").pop() ?? "";
const fileCode = fileName ? state.files[fileName] : "";
// TODO
const mainFile = fileName.endsWith(".mo")
? fileName
: state.files["Main.mo"]
? "Main.mo"
: "";
const mainFile =
fileExtension === "mo" ? fileName : state.files["Main.mo"] ? "Main.mo" : "";
const selectFrontend =
"package.json" in state.files &&
fileExtension !== "mo" &&
fileExtension !== "md";

const monaco = useMonaco();
const checkFileAddMarkers = async () => {
if (!fileName || !fileName.endsWith("mo")) return;
if (!fileName || fileExtension !== "mo") return;
const check = await worker.Moc({ type: "check", file: fileName });
const diags = check.diagnostics;
setMarkers(
Expand All @@ -137,7 +141,7 @@ export function Editor({
contents: newValue,
},
});
if (!fileName.endsWith("mo")) return;
if (fileExtension !== "mo") return;
await worker.Moc({ type: "save", file: fileName, content: newValue });
await checkFileAddMarkers();
};
Expand Down Expand Up @@ -169,11 +173,23 @@ export function Editor({
editorRef.current?.getAction("editor.action.formatDocument").run();
};
const deployClick = async () => {
if (selectFrontend) {
const files = convertNonMotokoFilesToWebContainer(state);
console.log(files);
await container.container!.fs.mkdir("user", { recursive: true });
await container.container!.mount(files, { mountPoint: "user" });
await container.run_cmd("npm", ["install"], { cwd: "user" });
await container.run_cmd("npm", ["run", "build"], { cwd: "user" });
const read = await container.container!.fs.readdir("/");
console.log(read);
return;
}
const aliases = getActorAliases(state.canisters);
await worker.saveWorkplaceToMotoko(state.files);
await worker.Moc({ type: "setActorAliases", list: aliases });
if (!mainFile) {
logger.log("Select a main entry file to deploy");
return;
}
const candid = await compileCandid(worker, mainFile, logger);
if (candid) {
Expand All @@ -200,7 +216,7 @@ export function Editor({
<PanelHeader>
Editor
<RightContainer>
{!!fileName.endsWith(".mo") && (
{fileExtension === "mo" && (
<>
{!!formatted && (
<FormatMessage>
Expand All @@ -226,19 +242,25 @@ export function Editor({
small
>
<img src={isDeploying ? iconSpin : iconRabbit} alt="Rabbit icon" />
<p>{isDeploying ? "Deploying..." : "Deploy"}</p>
<p>
{isDeploying
? "Deploying..."
: selectFrontend
? "Deploy Frontend"
: "Deploy Backend"}
</p>
</Button>
</RightContainer>
</PanelHeader>
<MarkdownContainer isHidden={!fileName.endsWith(".md")}>
<MarkdownContainer isHidden={fileExtension !== "md"}>
<ReactMarkdown linkTarget="_blank">
{fileName.endsWith(".md") ? fileCode : ""}
{fileExtension === "md" ? fileCode : ""}
</ReactMarkdown>
</MarkdownContainer>
<EditorContainer isHidden={fileName.endsWith(".md")}>
<EditorContainer isHidden={fileExtension === "md"}>
<MonacoEditor
defaultLanguage={"motoko"}
value={fileName.endsWith(".md") ? "" : fileCode}
value={fileExtension === "md" ? "" : fileCode}
path={fileName}
beforeMount={configureMonaco}
onMount={onEditorMount}
Expand Down
21 changes: 21 additions & 0 deletions src/contexts/WorkplaceState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,27 @@ export function getShareableProject(state: WorkplaceState) {
];
return { files, packages, canisters };
}
export function convertNonMotokoFilesToWebContainer(state: WorkplaceState) {
const files = Object.entries(state.files)
.filter(([path]) => !path.endsWith(".mo"))
.reduce((acc, [path, content]) => {
const parts = path.split("/");
let current = acc;
for (let i = 0; i < parts.length - 1; i++) {
if (!current[parts[i]]) {
current[parts[i]] = { directory: {} };
}
current = current[parts[i]].directory;
}
current[parts[parts.length - 1]] = {
file: {
contents: content,
},
};
return acc;
}, {});
return files;
}

export type WorkplaceReducerAction =
/**
Expand Down
6 changes: 3 additions & 3 deletions src/webcontainer.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { WebContainer, FileSystemTree } from "@webcontainer/api";
import { WebContainer, FileSystemTree, SpawnOptions } from "@webcontainer/api";
import { Terminal } from "@xterm/xterm";

export class Container {
Expand Down Expand Up @@ -52,10 +52,10 @@ export class Container {
await this.container!.mount(files);
}

async run_cmd(cmd: string, args: string[]) {
async run_cmd(cmd: string, args: string[], options?: SpawnOptions) {
await this.init();
this.terminal.writeln(`$ ${cmd} ${args.join(" ")}`);
const installProcess = await this.container!.spawn(cmd, args);
const installProcess = await this.container!.spawn(cmd, args, options);
installProcess.output.pipeTo(
new WritableStream({
write: (data) => {
Expand Down

0 comments on commit b7dad2d

Please sign in to comment.