ordinary 0.6.0-pre.11

Ordinary CLI
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
#![doc = include_str!("../docs/cli-reference.md")]
#![warn(clippy::all, clippy::pedantic)]
#![allow(clippy::missing_errors_doc)]

// Copyright (C) 2026 Ordinary Labs, LLC.
//
// SPDX-License-Identifier: AGPL-3.0-only

mod cmds;
mod permission;
mod units;

use clap::{Parser, Subcommand};
use clap_verbosity_flag::{Verbosity, WarnLevel};
use clio::ClioPath;
use std::path::Path;
use tracing::{Level, instrument};
use tracing_subscriber::fmt::format::FmtSpan;
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;

use crate::cmds::accounts::get_current_account;
use crate::cmds::secrets::Secrets;

use crate::cmds::root::Root;
use crate::cmds::ssg::Ssg;
use crate::cmds::utils::Utils;
pub use cmds::{
    accounts::Accounts, actions::Actions, app::App, assets::Assets, content::Content,
    integrations::Integrations, models::Models, templates::Templates,
};
use ordinary_api::client::OrdinaryApiClient;
use ordinary_config::OrdinaryConfig;
use ordinaryd::{AppApi, GlobalArgs};
pub use permission::Permission;

pub(crate) static USER_AGENT: &str =
    concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION"));

pub(crate) static GENERATOR: &str = concat!("Ordinary CLI ", env!("CARGO_PKG_VERSION"));

pub(crate) fn add_http(domain: &str, insecure: bool) -> String {
    if insecure {
        format!("http://{domain}")
    } else {
        format!("https://{domain}")
    }
}

#[derive(Parser, Debug)]
#[command(version, about, long_about = None)]
#[command(propagate_version = true)]
pub struct Cli {
    #[command(subcommand)]
    pub commands: Commands,

    /// project path
    #[arg(short, long, global = true, value_parser = clap::value_parser!(ClioPath).exists().is_dir(), default_value = ".")]
    pub project: ClioPath,

    /// should only be necessary with localhost or when addressing by IP
    #[arg(long, global = true)]
    pub api_domain: Option<String>,

    /// use HTTP instead of HTTPS
    #[arg(long, global = true, default_value_t = false)]
    pub insecure: bool,

    /// DANGER: only use when working with self-signed localhost certs
    #[arg(long, global = true, default_value_t = false)]
    pub danger_accept_invalid_certs: bool,

    #[command(flatten)]
    pub verbosity: Verbosity<WarnLevel>,

    /// whether to pretty print events to stdio
    #[arg(long, global = true, default_value_t = false)]
    pub pretty: bool,
}

#[derive(Subcommand, Debug)]
pub enum Commands {
    /// create a new Ordinary project
    New {
        /// project domain
        domain: String,
        /// project path
        #[arg(long, default_value = ".")]
        path: String,
    },
    /// manage static site configuration
    Ssg {
        #[command(subcommand)]
        ssg: Ssg,
    },
    /// build your Ordinary project
    ///
    /// Note: will load environment variables from `.env`
    Build {
        /// build project without checking the cache
        #[arg(short, long, default_value_t = false)]
        ignore_cache: bool,
    },
    /// start the app, locally
    Start {
        #[command(flatten)]
        app_api: AppApi,

        #[command(flatten)]
        global_args: GlobalArgs,

        /// disables these defaults set for development:
        /// `--stdio-logs`
        /// `--stdio-logs-fmt concise`
        /// `--insecure`
        /// `--insecure-cookies`
        #[arg(short, long, default_value_t = false)]
        disable_defaults: bool,
    },
    /// combines `build`, `content update`, `assets write`,
    /// `templates upload`, `actions install`
    Publish,

    /// manage templates in your Ordinary project
    Templates {
        #[command(subcommand)]
        templates: Templates,
    },
    /// manage content in your Ordinary project
    Content {
        #[command(subcommand)]
        content: Content,
    },
    /// manage assets in your Ordinary project
    Assets {
        #[command(subcommand)]
        assets: Assets,
    },

    /// manage models in your Ordinary project
    Models {
        #[command(subcommand)]
        models: Models,
    },
    /// manage actions in your Ordinary project
    Actions {
        #[command(subcommand)]
        actions: Actions,
    },
    /// manage integrations in your Ordinary project
    Integrations {
        #[command(subcommand)]
        integrations: Integrations,
    },

    /// manage accounts connected to `ordinaryd`
    Accounts {
        #[command(subcommand)]
        accounts: Accounts,
    },
    /// manage applications running on `ordinaryd`
    App {
        #[command(subcommand)]
        app: App,
    },
    /// manage secrets in your Ordinary application
    Secrets {
        #[command(subcommand)]
        secrets: Secrets,
    },
    Root {
        #[command(subcommand)]
        root: Root,
    },
    /// ensure that all the correct system components are installed
    Doctor {
        /// auto fix installs
        #[arg(short, long, value_delimiter = ',', num_args = 1..)]
        fix: Option<Vec<ordinary_doctor::Fix>>,
    },
    /// utility functions for aiding project development
    Utils {
        #[command(subcommand)]
        utils: Utils,
    },
}

pub fn setup(cli: &Cli) -> anyhow::Result<()> {
    let pretty_layer = if cli.pretty {
        Some(
            tracing_subscriber::fmt::layer()
                .pretty()
                .with_span_events(FmtSpan::CLOSE)
                .with_writer(std::io::stderr),
        )
    } else {
        None
    };

    let ugly_layer = if cli.pretty {
        None
    } else {
        Some(
            tracing_subscriber::fmt::layer()
                .with_span_events(FmtSpan::CLOSE)
                .with_target(false)
                .with_writer(std::io::stderr),
        )
    };

    let log_level_str = cli
        .verbosity
        .tracing_level()
        .unwrap_or(Level::INFO)
        .as_str()
        .to_ascii_lowercase();

    let directives = [
        ("ordinaryd", &log_level_str),            // daemon
        ("ordinary_modify", &log_level_str),      // modify
        ("ordinary_build", &log_level_str),       // build
        ("ordinary_doctor", &log_level_str),      // doctor
        ("ordinary_studio", &log_level_str),      // studio
        ("ordinary_utils", &log_level_str),       // utils
        ("ordinary_auth", &log_level_str),        // auth
        ("ordinary_api", &log_level_str),         // api
        ("ordinary_app", &log_level_str),         // app
        ("ordinary_template", &log_level_str),    // templates
        ("ordinary_action", &log_level_str),      // actions
        ("ordinary_integration", &log_level_str), // integrations
        ("ordinary_storage", &log_level_str),     // storage
        ("ordinary_monitor", &log_level_str),     // monitor
        ("ordinary_config", &log_level_str),      // config
        ("tower_http", &log_level_str),           // http
    ];

    let mut directives_string = format!("ordinary={}", &log_level_str);

    for (lib, lvl) in directives {
        directives_string = format!("{directives_string},{lib}={lvl}");
    }

    tracing_subscriber::registry()
        .with(
            tracing_subscriber::EnvFilter::try_from_default_env()
                .unwrap_or_else(|_| directives_string.into()),
        )
        .with(pretty_layer)
        .with(ugly_layer)
        .init();

    std::panic::set_hook(Box::new(|info| {
        if let Some(msg) = info.payload_as_str()
            && let Some(loc) = info.location()
        {
            tracing::error!(%loc, msg, "panic");
        } else if let Some(loc) = info.location() {
            tracing::error!(%loc, "panic");
        }
    }));

    Ok(())
}

#[allow(clippy::too_many_lines, clippy::missing_panics_doc)]
#[instrument(name = "ordinary", skip_all, err)]
pub async fn run(cli: &Cli) -> anyhow::Result<()> {
    let api_domain = cli.api_domain.as_deref();

    let project = cli
        .project
        .to_str()
        .expect("failed to get string from path");

    match &cli.commands {
        Commands::New { path, domain } => ordinary_modify::project::new(path, domain)?,
        Commands::Ssg { ssg } => {
            ssg.handle(project)?;
        }
        Commands::Build { ignore_cache } => {
            let env_file = Path::new(project).join(".env");
            if env_file.exists() {
                dotenv::from_path(env_file)?;
            }

            ordinary_build::build(project, *ignore_cache, "ordinary")?;
        }
        Commands::Publish => {
            let env_file = Path::new(project).join(".env");
            if env_file.exists() {
                dotenv::from_path(env_file)?;
            }

            ordinary_build::build(project, true, GENERATOR)?;

            let account = get_current_account(cli.insecure)?;
            let client = OrdinaryApiClient::new(
                &account.host,
                &account.name,
                api_domain,
                cli.danger_accept_invalid_certs,
                USER_AGENT,
                true,
            )?;

            let config = OrdinaryConfig::get(project)?;

            client.deploy(project).await?;

            if config.content.is_some() {
                client.update(project).await?;
            }

            if config.assets.is_some() {
                client.write_all(project).await?;
            }

            if config.templates.is_some() {
                client.upload_all(project).await?;
            }

            if config.actions.is_some() {
                client.install_all(project).await?;
            }
        }
        Commands::Templates { templates } => {
            templates
                .handle(
                    api_domain,
                    cli.danger_accept_invalid_certs,
                    project,
                    cli.insecure,
                )
                .await?;
        }
        Commands::Content { content } => {
            content
                .handle(
                    api_domain,
                    cli.danger_accept_invalid_certs,
                    project,
                    cli.insecure,
                )
                .await?;
        }
        Commands::Assets { assets } => {
            assets
                .handle(
                    api_domain,
                    cli.danger_accept_invalid_certs,
                    project,
                    cli.insecure,
                )
                .await?;
        }
        Commands::Models { models } => {
            models
                .handle(
                    api_domain,
                    cli.danger_accept_invalid_certs,
                    project,
                    cli.insecure,
                )
                .await?;
        }
        Commands::Actions { actions } => {
            actions
                .handle(
                    api_domain,
                    cli.danger_accept_invalid_certs,
                    project,
                    cli.insecure,
                )
                .await?;
        }
        Commands::Integrations { integrations } => {
            integrations.handle(project)?;
        }
        Commands::Accounts { accounts } => {
            accounts
                .handle(api_domain, cli.danger_accept_invalid_certs, cli.insecure)
                .await?;
        }
        Commands::App { app } => {
            let env_file = Path::new(project).join(".env");
            if env_file.exists() {
                dotenv::from_path(env_file)?;
            }

            app.handle(
                api_domain,
                cli.danger_accept_invalid_certs,
                project,
                cli.insecure,
            )
            .await?;
        }
        Commands::Secrets { secrets } => {
            secrets
                .handle(
                    api_domain,
                    cli.danger_accept_invalid_certs,
                    project,
                    cli.insecure,
                )
                .await?;
        }
        Commands::Root { root } => {
            root.handle(api_domain, cli.danger_accept_invalid_certs, cli.insecure)
                .await?;
        }
        Commands::Doctor { fix } => {
            ordinary_doctor::doctor(&fix.clone().unwrap_or(vec![]))?;
        }
        Commands::Utils { utils } => {
            utils.handle()?;
        }
        Commands::Start { .. } => unreachable!("checked in main.rs"),
    }

    Ok(())
}