aboutsummaryrefslogtreecommitdiffstats
path: root/vespaclient-java/src/main/java/com/yahoo/vespa/security/tool/CliUtils.java
blob: b09ae17cd77f07b1c72d102256f25a04194bd9a7 (plain) (blame)
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
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.security.tool;

import org.apache.commons.cli.CommandLine;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.attribute.PosixFilePermissions;

/**
 * @author vekterli
 */
public class CliUtils {

    public static String optionOrThrow(CommandLine arguments, String option) {
        var value = arguments.getOptionValue(option);
        if (value == null) {
            throw new IllegalArgumentException("Required argument '--%s' must be provided".formatted(option));
        }
        return value;
    }

    public static boolean useStdIo(String pathOrDash) {
        return "-".equals(pathOrDash);
    }

    public static InputStream inputStreamFromFileOrStream(String pathOrDash, InputStream stdIn) throws IOException {
        if (useStdIo(pathOrDash)) {
            return stdIn;
        } else {
            var inputPath = Paths.get(pathOrDash);
            if (!Files.exists(inputPath)) {
                throw new IllegalArgumentException("Input file '%s' does not exist".formatted(inputPath.toString()));
            }
            return Files.newInputStream(inputPath);
        }
    }

    public static OutputStream outputStreamToFileOrStream(String pathOrDash, OutputStream stdOut) throws IOException {
        if (useStdIo(pathOrDash)) {
            return stdOut;
        } else {
            // TODO fail if file already exists?
            var privFilePerms = PosixFilePermissions.fromString("rw-------");
            var outPath = Paths.get(pathOrDash);
            Files.createFile(outPath, PosixFilePermissions.asFileAttribute(privFilePerms));
            return Files.newOutputStream(outPath);
        }
    }

}