or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

annotations.mdautocompletion.mdcommand-line.mdhelp-system.mdindex.mdparsing-execution.mdtype-conversion.md

command-line.mddocs/

0

# CommandLine Core

1

2

Central command line parsing and execution functionality including argument parsing, subcommand handling, configuration options, and execution strategies. The CommandLine class serves as the main entry point for all picocli functionality.

3

4

## Capabilities

5

6

### CommandLine Class

7

8

Main class for parsing command line arguments and executing commands with extensive configuration options.

9

10

```java { .api }

11

public class CommandLine {

12

public static final String VERSION = "4.7.7";

13

14

/**

15

* Creates a CommandLine instance from an annotated command object

16

* @param command the annotated command object

17

*/

18

public CommandLine(Object command);

19

20

/**

21

* Creates a CommandLine instance with a custom factory

22

* @param command the annotated command object

23

* @param factory factory for creating instances of command classes

24

*/

25

public CommandLine(Object command, IFactory factory);

26

27

/**

28

* Parses and executes the command with the specified arguments

29

* @param args the command line arguments

30

* @return exit code (0 for success, non-zero for errors)

31

*/

32

public int execute(String... args);

33

34

/**

35

* Parses command line arguments without executing

36

* @param args the command line arguments to parse

37

* @return ParseResult containing parsed arguments

38

*/

39

public ParseResult parseArgs(String... args);

40

41

/**

42

* Gets the parse result from the last parsing operation

43

* @return ParseResult or null if no parsing has occurred

44

*/

45

public ParseResult getParseResult();

46

47

/**

48

* Gets the command specification for this CommandLine

49

* @return the CommandSpec model

50

*/

51

public CommandSpec getCommandSpec();

52

53

/**

54

* Gets the command object instance

55

* @return the command instance

56

*/

57

public <T> T getCommand();

58

59

// Configuration Methods

60

public boolean isPosixClusteredShortOptionsAllowed();

61

public CommandLine setPosixClusteredShortOptionsAllowed(boolean newValue);

62

public boolean isCaseInsensitiveEnumValuesAllowed();

63

public CommandLine setCaseInsensitiveEnumValuesAllowed(boolean newValue);

64

public boolean isTrimQuotes();

65

public CommandLine setTrimQuotes(boolean newValue);

66

public String getEndOfOptionsDelimiter();

67

public CommandLine setEndOfOptionsDelimiter(String delimiter);

68

public boolean isSubcommandsCaseInsensitive();

69

public CommandLine setSubcommandsCaseInsensitive(boolean newValue);

70

public boolean isOptionsCaseInsensitive();

71

public CommandLine setOptionsCaseInsensitive(boolean newValue);

72

public boolean isAbbreviatedSubcommandsAllowed();

73

public CommandLine setAbbreviatedSubcommandsAllowed(boolean newValue);

74

public boolean isAbbreviatedOptionsAllowed();

75

public CommandLine setAbbreviatedOptionsAllowed(boolean newValue);

76

public boolean isOverwrittenOptionsAllowed();

77

public CommandLine setOverwrittenOptionsAllowed(boolean newValue);

78

public boolean isStopAtPositional();

79

public CommandLine setStopAtPositional(boolean newValue);

80

public boolean isStopAtUnmatched();

81

public CommandLine setStopAtUnmatched(boolean newValue);

82

public boolean isUnmatchedArgumentsAllowed();

83

public CommandLine setUnmatchedArgumentsAllowed(boolean newValue);

84

public List<String> getUnmatchedArguments();

85

86

// I/O Configuration

87

public PrintWriter getOut();

88

public CommandLine setOut(PrintWriter out);

89

public PrintWriter getErr();

90

public CommandLine setErr(PrintWriter err);

91

public Help.ColorScheme getColorScheme();

92

public CommandLine setColorScheme(Help.ColorScheme colorScheme);

93

94

// Help Methods

95

public Help getHelp();

96

public IHelpFactory getHelpFactory();

97

public CommandLine setHelpFactory(IHelpFactory helpFactory);

98

public void usage(PrintStream out);

99

public void usage(PrintWriter writer);

100

public void usage(PrintStream out, Help.Ansi ansi);

101

public void usage(PrintWriter writer, Help.ColorScheme colorScheme);

102

public String getUsageMessage();

103

public String getUsageMessage(Help.Ansi ansi);

104

public String getUsageMessage(Help.ColorScheme colorScheme);

105

public void printVersionHelp(PrintStream out);

106

public void printVersionHelp(PrintWriter out, Help.Ansi ansi, Object... params);

107

108

// Exception Handling

109

public IExitCodeExceptionMapper getExitCodeExceptionMapper();

110

public CommandLine setExitCodeExceptionMapper(IExitCodeExceptionMapper mapper);

111

public IExecutionStrategy getExecutionStrategy();

112

public CommandLine setExecutionStrategy(IExecutionStrategy executionStrategy);

113

public IParameterExceptionHandler getParameterExceptionHandler();

114

public CommandLine setParameterExceptionHandler(IParameterExceptionHandler handler);

115

public IExecutionExceptionHandler getExecutionExceptionHandler();

116

public CommandLine setExecutionExceptionHandler(IExecutionExceptionHandler handler);

117

}

118

```

119

120

**Usage Examples:**

121

122

```java

123

// Basic execution

124

@Command(name = "myapp")

125

class MyApp implements Runnable {

126

@Option(names = "-v") boolean verbose;

127

128

public void run() {

129

System.out.println("Running " + (verbose ? "verbosely" : "quietly"));

130

}

131

}

132

133

public static void main(String[] args) {

134

int exitCode = new CommandLine(new MyApp()).execute(args);

135

System.exit(exitCode);

136

}

137

138

// Parse without executing

139

CommandLine cmd = new CommandLine(new MyApp());

140

ParseResult parseResult = cmd.parseArgs("-v", "input.txt");

141

if (parseResult.hasMatchedOption("-v")) {

142

System.out.println("Verbose flag was set");

143

}

144

```

145

146

### Subcommand Management

147

148

Methods for adding and managing subcommands in hierarchical command structures.

149

150

```java { .api }

151

/**

152

* Adds a subcommand with the class name as command name

153

* @param command the subcommand object

154

* @return this CommandLine instance for method chaining

155

*/

156

public CommandLine addSubcommand(Object command);

157

158

/**

159

* Adds a subcommand with specified name

160

* @param name the command name

161

* @param command the subcommand object

162

* @return this CommandLine instance for method chaining

163

*/

164

public CommandLine addSubcommand(String name, Object command);

165

166

/**

167

* Adds a subcommand with name and aliases

168

* @param name the command name

169

* @param command the subcommand object

170

* @param aliases alternative names for the command

171

* @return this CommandLine instance for method chaining

172

*/

173

public CommandLine addSubcommand(String name, Object command, String... aliases);

174

175

/**

176

* Gets all registered subcommands

177

* @return map of command names to CommandLine instances

178

*/

179

public Map<String, CommandLine> getSubcommands();

180

181

/**

182

* Gets the parent CommandLine if this is a subcommand

183

* @return parent CommandLine or null if this is the root command

184

*/

185

public CommandLine getParent();

186

```

187

188

**Usage Example:**

189

190

```java

191

@Command(name = "git")

192

class Git implements Runnable {

193

public void run() { /* show general help */ }

194

}

195

196

@Command(name = "add")

197

class GitAdd implements Runnable {

198

@Parameters String[] files;

199

public void run() { /* implement git add */ }

200

}

201

202

@Command(name = "commit")

203

class GitCommit implements Runnable {

204

@Option(names = "-m") String message;

205

public void run() { /* implement git commit */ }

206

}

207

208

// Set up command hierarchy

209

CommandLine git = new CommandLine(new Git());

210

git.addSubcommand("add", new GitAdd());

211

git.addSubcommand("commit", new GitCommit());

212

213

// Execute: git add file1.txt file2.txt

214

int exitCode = git.execute("add", "file1.txt", "file2.txt");

215

```

216

217

### Configuration Options

218

219

Methods for configuring parsing behavior and command execution.

220

221

```java { .api }

222

/**

223

* Sets whether boolean flags can be toggled with += syntax

224

*/

225

public CommandLine setToggleBooleanFlags(boolean newValue);

226

public boolean isToggleBooleanFlags();

227

228

/**

229

* Sets whether options can be overwritten by later occurrences

230

*/

231

public CommandLine setOverwrittenOptionsAllowed(boolean newValue);

232

public boolean isOverwrittenOptionsAllowed();

233

234

/**

235

* Sets whether POSIX-style clustered short options are allowed (-abc = -a -b -c)

236

*/

237

public CommandLine setPosixClusteredShortOptionsAllowed(boolean newValue);

238

public boolean isPosixClusteredShortOptionsAllowed();

239

240

/**

241

* Sets whether enum values are case insensitive

242

*/

243

public CommandLine setCaseInsensitiveEnumValuesAllowed(boolean newValue);

244

public boolean isCaseInsensitiveEnumValuesAllowed();

245

246

/**

247

* Sets whether quotes are trimmed from option values

248

*/

249

public CommandLine setTrimQuotes(boolean newValue);

250

public boolean isTrimQuotes();

251

252

/**

253

* Sets whether subcommands are case insensitive

254

*/

255

public CommandLine setSubcommandsCaseInsensitive(boolean newValue);

256

public boolean isSubcommandsCaseInsensitive();

257

258

/**

259

* Sets whether options are case insensitive

260

*/

261

public CommandLine setOptionsCaseInsensitive(boolean newValue);

262

public boolean isOptionsCaseInsensitive();

263

264

/**

265

* Sets whether abbreviated subcommands are allowed

266

*/

267

public CommandLine setAbbreviatedSubcommandsAllowed(boolean newValue);

268

public boolean isAbbreviatedSubcommandsAllowed();

269

270

/**

271

* Sets whether abbreviated options are allowed

272

*/

273

public CommandLine setAbbreviatedOptionsAllowed(boolean newValue);

274

public boolean isAbbreviatedOptionsAllowed();

275

276

/**

277

* Sets whether parsing stops at first positional parameter

278

*/

279

public CommandLine setStopAtPositional(boolean newValue);

280

public boolean isStopAtPositional();

281

282

/**

283

* Sets whether parsing stops at first unmatched argument

284

*/

285

public CommandLine setStopAtUnmatched(boolean newValue);

286

public boolean isStopAtUnmatched();

287

288

/**

289

* Sets the end-of-options delimiter (default: "--")

290

*/

291

public CommandLine setEndOfOptionsDelimiter(String delimiter);

292

public String getEndOfOptionsDelimiter();

293

```

294

295

**Usage Example:**

296

297

```java

298

CommandLine cmd = new CommandLine(new MyApp());

299

300

// Configure parsing behavior

301

cmd.setPosixClusteredShortOptionsAllowed(true) // Allow -abc

302

.setCaseInsensitiveEnumValuesAllowed(true) // Case insensitive enums

303

.setToggleBooleanFlags(false) // Disable toggle syntax

304

.setTrimQuotes(true) // Trim quotes from values

305

.setAbbreviatedOptionsAllowed(true); // Allow abbreviated options

306

307

int exitCode = cmd.execute(args);

308

```

309

310

### Factory and Provider Configuration

311

312

Methods for configuring factories and providers for customization.

313

314

```java { .api }

315

/**

316

* Gets the factory used for creating command instances

317

*/

318

public IFactory getFactory();

319

320

/**

321

* Sets the default value provider for options and parameters

322

*/

323

public CommandLine setDefaultValueProvider(IDefaultValueProvider provider);

324

public IDefaultValueProvider getDefaultValueProvider();

325

326

/**

327

* Sets the help factory for custom help generation

328

*/

329

public CommandLine setHelpFactory(IHelpFactory helpFactory);

330

public IHelpFactory getHelpFactory();

331

```

332

333

### Help Generation

334

335

Methods for generating and customizing usage help messages.

336

337

```java { .api }

338

/**

339

* Gets the Help object for this command

340

*/

341

public Help getHelp();

342

343

/**

344

* Checks if help was requested in the last parse operation

345

*/

346

public boolean isUsageHelpRequested();

347

348

/**

349

* Checks if version help was requested in the last parse operation

350

*/

351

public boolean isVersionHelpRequested();

352

353

/**

354

* Gets the list of help section keys in display order

355

*/

356

public List<String> getHelpSectionKeys();

357

358

/**

359

* Sets the help section keys in display order

360

*/

361

public CommandLine setHelpSectionKeys(List<String> keys);

362

363

/**

364

* Gets the map of help section renderers

365

*/

366

public Map<String, IHelpSectionRenderer> getHelpSectionMap();

367

368

/**

369

* Sets the map of help section renderers

370

*/

371

public CommandLine setHelpSectionMap(Map<String, IHelpSectionRenderer> map);

372

```

373

374

### Static Utility Methods

375

376

Convenience methods for common operations without creating CommandLine instances.

377

378

```java { .api }

379

/**

380

* Populates an annotated command object with parsed arguments

381

*/

382

public static <T> T populateCommand(T command, String... args);

383

384

/**

385

* Populates a command specification class with parsed arguments

386

*/

387

public static <T> T populateSpec(Class<T> spec, String... args);

388

389

/**

390

* Prints usage help for a command to System.out

391

*/

392

public static void usage(Object command, PrintStream out);

393

public static void usage(Object command, PrintStream out, Help.Ansi ansi);

394

public static void usage(Object command, PrintStream out, Help.ColorScheme colorScheme);

395

396

/**

397

* Handles help requests from parse results

398

*/

399

public static boolean printHelpIfRequested(ParseResult parseResult);

400

public static Integer executeHelpRequest(ParseResult parseResult);

401

402

/**

403

* Gets methods annotated with @Command in a class

404

*/

405

public static List<Method> getCommandMethods(Class<?> cls, String methodName);

406

407

/**

408

* Gets the default factory instance

409

*/

410

public static IFactory defaultFactory();

411

412

/**

413

* Gets the default exception handler

414

*/

415

public static DefaultExceptionHandler<List<Object>> defaultExceptionHandler();

416

```

417

418

**Usage Examples:**

419

420

```java

421

// Quick population without CommandLine instance

422

@Command(name = "quick")

423

class QuickCommand {

424

@Option(names = "-v") boolean verbose;

425

@Parameters String[] files;

426

}

427

428

QuickCommand cmd = CommandLine.populateCommand(new QuickCommand(), args);

429

430

// Print usage help

431

CommandLine.usage(new MyCommand(), System.out);

432

433

// Handle help requests

434

ParseResult parseResult = commandLine.parseArgs(args);

435

if (CommandLine.printHelpIfRequested(parseResult)) {

436

return; // Help was printed, exit

437

}

438

```

439

440

## Supporting Interfaces

441

442

```java { .api }

443

/**

444

* Factory for creating instances of command classes

445

*/

446

public interface IFactory {

447

<K> K create(Class<K> cls) throws Exception;

448

}

449

450

/**

451

* Strategy for executing parsed commands

452

*/

453

public interface IExecutionStrategy {

454

int execute(ParseResult parseResult) throws ExecutionException;

455

}

456

457

/**

458

* Handles parameter parsing exceptions

459

*/

460

public interface IParameterExceptionHandler {

461

int handleParseException(ParameterException ex, String[] args) throws Exception;

462

}

463

464

/**

465

* Handles execution exceptions

466

*/

467

public interface IExecutionExceptionHandler {

468

int handleExecutionException(Exception ex, CommandLine commandLine, ParseResult parseResult) throws Exception;

469

}

470

```

471

472

### Static Convenience Methods

473

474

Utility methods for common operations without needing to create CommandLine instances explicitly.

475

476

```java { .api }

477

/**

478

* Parses the specified command line arguments and populates the annotated fields and methods

479

* @param command the command object to populate

480

* @param args the command line arguments

481

* @return the populated command object

482

*/

483

public static <T> T populateCommand(T command, String... args);

484

485

/**

486

* Parses the specified command line arguments and populates a new instance of the specified class

487

* @param spec the command class

488

* @param args the command line arguments

489

* @return the populated command instance

490

*/

491

public static <T> T populateSpec(Class<T> spec, String... args);

492

493

/**

494

* Delegates to {@link #usage(Object, PrintStream, Help.Ansi)} with the platform default Ansi setting

495

*/

496

public static void usage(Object command, PrintStream out);

497

498

/**

499

* Delegates to {@link #usage(Object, PrintStream, Help.ColorScheme)} with a default color scheme

500

*/

501

public static void usage(Object command, PrintStream out, Help.Ansi ansi);

502

503

/**

504

* Prints usage help message for the specified command to the specified PrintStream

505

*/

506

public static void usage(Object command, PrintStream out, Help.ColorScheme colorScheme);

507

508

/**

509

* Returns true if help was requested, after printing help if requested

510

*/

511

public static boolean printHelpIfRequested(ParseResult parseResult);

512

513

/**

514

* Executes help request if any, returns exit code or null if no help was requested

515

*/

516

public static Integer executeHelpRequest(ParseResult parseResult);

517

518

/**

519

* Returns the list of annotated methods in the specified class with the specified name

520

*/

521

public static List<Method> getCommandMethods(Class<?> cls, String methodName);

522

```