001/*
002 * SPDX-License-Identifier: Apache-2.0
003 *
004 * Copyright 2024-2026 The Enola <https://enola.dev> Authors
005 *
006 * Licensed under the Apache License, Version 2.0 (the "License");
007 * you may not use this file except in compliance with the License.
008 * You may obtain a copy of the License at
009 *
010 *     https://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package dev.enola.common;
019
020import java.net.URI;
021
022public record URILineColumnMessage(String message, URI uri, long line, long column) {
023
024    public URILineColumnMessage(String message, URI uri, long line) {
025        this(message, uri, line, -1);
026    }
027
028    public String format() {
029        // TODO Have some way of globally configuring default output format
030        return format(Format.GCC);
031    }
032
033    public String format(Format format) {
034        return switch (format) {
035            case GCC -> forGCC();
036            case VS -> forVS();
037            case JSON -> asJSON();
038        };
039    }
040
041    public enum Format {
042        GCC,
043        VS,
044        JSON
045    }
046
047    private String forGCC() {
048        return uri() + ":" + line + optionalColumn(":") + ": " + message;
049    }
050
051    private String forVS() {
052        return uri() + "(" + line + optionalColumn(",") + "): " + message;
053    }
054
055    private String asJSON() {
056        var sb = new StringBuilder("{ \"file\": \"").append(uri);
057        sb.append("\", \"line\": ").append(line);
058        if (column > -1) {
059            sb.append(" \"column\": ").append(column);
060        }
061        sb.append(" \"message\": ").append(message);
062        sb.append(" }");
063        return sb.toString();
064    }
065
066    private String optionalColumn(String separator) {
067        if (column > -1) {
068            return separator + column;
069        } else return "";
070    }
071}