Skip to content

Commit b73f126

Browse files
committed
Added new codify file resolution logic. WIP default document endpoint fetch
1 parent 38b2414 commit b73f126

File tree

4 files changed

+78
-36
lines changed

4 files changed

+78
-36
lines changed

src/api/dashboard/index.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,5 +21,24 @@ export const DashboardApiClient = {
2121
}
2222

2323
return json;
24+
},
25+
26+
async getDefaultDocumentId(): Promise<string> {
27+
const login = LoginHelper.get()?.credentials;
28+
if (!login) {
29+
throw new Error('Not logged in');
30+
}
31+
32+
// const res = await fetch(
33+
// `${API_BASE_URL}/api/v1/documents/default/id`,
34+
// { method: 'GET', headers: { 'Content-Type': 'application/json', 'authorization': login.accessToken } },
35+
// );
36+
37+
// const json = await res.json();
38+
// if (!res.ok) {
39+
// throw new Error(JSON.stringify(json, null, 2));
40+
// }
41+
42+
return '1b80818e-5304-4158-80a3-82e17ff2c79e';
2443
}
2544
}

src/common/initialize-plugins.ts

Lines changed: 55 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,9 @@ import { CODIFY_FILE_REGEX, CodifyParser } from '../parser/index.js';
88
import { DependencyMap, PluginManager } from '../plugins/plugin-manager.js';
99
import { Reporter } from '../ui/reporters/reporter.js';
1010
import { LoginHelper } from '../connect/login-helper.js';
11+
import { FileUtils } from '../utils/file.js';
12+
import { validate } from 'uuid';
13+
import { DashboardApiClient } from '../api/dashboard/index.js';
1114

1215
export interface InitializeArgs {
1316
path?: string;
@@ -28,11 +31,11 @@ export class PluginInitOrchestrator {
2831
args: InitializeArgs,
2932
reporter: Reporter,
3033
): Promise<InitializationResult> {
34+
const codifyPath = await PluginInitOrchestrator.resolveCodifyRootPath(args, reporter);
35+
3136
let project = await PluginInitOrchestrator.parse(
32-
args.path,
33-
args.allowEmptyProject ?? false,
34-
reporter
35-
)
37+
codifyPath,
38+
);
3639
if (args.transformProject) {
3740
project = await args.transformProject(project);
3841
}
@@ -47,32 +50,9 @@ export class PluginInitOrchestrator {
4750

4851
private static async parse(
4952
fileOrDir: string | undefined,
50-
allowEmptyProject: boolean,
51-
reporter: Reporter
5253
): Promise<Project> {
5354
ctx.subprocessStarted(SubProcessName.PARSE);
5455

55-
const isLoggedIn = LoginHelper.get()?.isLoggedIn ?? false;
56-
57-
if (!fileOrDir && !allowEmptyProject && !isLoggedIn) {
58-
ctx.subprocessFinished(SubProcessName.PARSE);
59-
ctx.subprocessStarted(SubProcessName.CREATE_ROOT_FILE)
60-
const createRootCodifyFile = await reporter.promptConfirmation('\nNo codify file found. Do you want to create a root file at ~/codify.jsonc?');
61-
62-
if (createRootCodifyFile) {
63-
await fs.writeFile(
64-
path.resolve(os.homedir(), 'codify.jsonc'),
65-
'[]',
66-
{ encoding: 'utf8', flag: 'wx' }
67-
); // flag: 'wx' prevents overwrites if the file exists
68-
}
69-
70-
ctx.subprocessFinished(SubProcessName.CREATE_ROOT_FILE)
71-
72-
console.log('Created ~/codify.jsonc file')
73-
process.exit(0);
74-
}
75-
7656
const project = fileOrDir
7757
? await CodifyParser.parse(fileOrDir)
7858
: Project.empty()
@@ -82,19 +62,59 @@ export class PluginInitOrchestrator {
8262
return project
8363
}
8464

85-
private static async findCodifyJson(dir?: string): Promise<null | string> {
86-
dir = dir ?? process.cwd();
65+
/** Resolve the root codify file to run.
66+
* Order:
67+
* 1. If path is specified, return that.
68+
* 2. If path is a dir with only one *codify.json|*codify.jsonc|*codify.json5|*codify.yaml, return that.
69+
* 3. If path is a UUID, return file from Codify cloud.
70+
* 4. If multiple exists in the path (dir), then prompt the user to select one.
71+
* 5. If no path is provided, run steps 2 - 4 for the current dir.
72+
* 6. If none exists, return default file from codify cloud.
73+
* 7. If user is not logged in, return an error.
74+
*
75+
* @param args
76+
* @private
77+
*/
78+
private static async resolveCodifyRootPath(args: InitializeArgs, reporter: Reporter): Promise<string | undefined> {
79+
const inputPath = args.path ?? process.cwd();
80+
81+
// Cloud files will be fetched and processed later in the parser.
82+
const isCloud = validate(inputPath);
83+
if (isCloud) {
84+
return inputPath;
85+
}
86+
87+
// Direct files can have its path returned.
88+
const isPathDir = await FileUtils.isDir(inputPath);
89+
if (!isPathDir) {
90+
return inputPath;
91+
}
92+
93+
const filesInDir = await fs.readdir(inputPath);
94+
const codifyFiles = filesInDir.filter((f) => CODIFY_FILE_REGEX.test(f))
95+
96+
if (codifyFiles.length === 1) {
97+
return codifyFiles[0];
98+
}
99+
100+
if (codifyFiles.length > 0) {
101+
const answer = await reporter.promptOptions(
102+
'Multiple codify files found in dir. Please select one:',
103+
codifyFiles,
104+
);
105+
106+
return path.join(inputPath, codifyFiles[answer]);
107+
}
87108

88-
const filesInDir = await fs.readdir(dir);
89-
if (filesInDir.some((f) => CODIFY_FILE_REGEX.test(f))) {
90-
return dir;
109+
if (LoginHelper.get()?.isLoggedIn) {
110+
return DashboardApiClient.getDefaultDocumentId();
91111
}
92112

93-
if (dir.includes(os.homedir()) && dir !== os.homedir()) {
94-
return this.findCodifyJson(path.dirname(dir))
113+
if (args.allowEmptyProject) {
114+
return undefined;
95115
}
96116

97-
return null;
117+
throw new Error('No codify files found.');
98118
}
99119

100120
}

src/parser/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,7 @@ class Parser {
7171

7272
return Promise.all(filePaths.map(
7373
async (p) => {
74+
// If path is a uuid and doesn't exist as a file, it's a cloud file
7475
if (validate(p) && !(await FileUtils.fileExists(p))) {
7576
return cloudReader.read(p)
7677
}

src/ui/reporters/default-reporter.tsx

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -219,6 +219,8 @@ export class DefaultReporter implements Reporter {
219219
}
220220

221221
async promptOptions(message:string, options:string[]): Promise<number> {
222+
const prevRenderState = this.getRenderState();
223+
222224
const result = await this.updateStateAndAwaitEvent<string>(
223225
() => this.updateRenderState(RenderStatus.PROMPT_OPTIONS, { message, options }),
224226
RenderEvent.PROMPT_RESULT
@@ -229,7 +231,7 @@ export class DefaultReporter implements Reporter {
229231
// This was added because there was a very hard to debug memory bug with Yoga (ink.js layout engine). Could not
230232
// identify the root cause of the problem but this alleviates it.
231233
await sleep(50)
232-
this.updateRenderState(RenderStatus.NOTHING, null);
234+
this.updateRenderState(prevRenderState.status, prevRenderState.data);
233235
await sleep(50);
234236

235237
return options.indexOf(result);

0 commit comments

Comments
 (0)