version

package
v1.199.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 8, 2026 License: Apache-2.0 Imports: 12 Imported by: 0

Documentation

Overview

* ChatCLI - Command Line Interface for LLM interaction * Copyright (c) 2024 Edilson Freitas * License: Apache-2.0

* ChatCLI - Command Line Interface for LLM interaction * Copyright (c) 2024 Edilson Freitas * License: Apache-2.0

* ChatCLI - Command Line Interface for LLM interaction * Copyright (c) 2024 Edilson Freitas * License: Apache-2.0

Index

Constants

This section is empty.

Variables

View Source
var (
	// Essas variáveis serão preenchidas durante a compilação via ldflags
	Version    = "dev"
	CommitHash = "unknown"
	BuildDate  = "unknown"

	// URL para verificar a versão mais recente (GitHub API)
	LatestVersionURL = "https://api.github.com/repos/diillson/chatcli/releases/latest"
)
View Source
var FetchLatestReleaseImpl = func(ctx context.Context) (ReleaseInfo, error) {
	client := &http.Client{
		Timeout: 10 * time.Second,
	}

	url := os.Getenv("CHATCLI_LATEST_VERSION_URL")
	if url == "" {
		url = LatestVersionURL
	}

	req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
	if err != nil {
		return ReleaseInfo{}, err
	}

	req.Header.Set("User-Agent", "ChatCLI-Version-Checker")

	resp, err := client.Do(req)
	if err != nil {
		return ReleaseInfo{}, err
	}
	defer func() {
		if closeErr := resp.Body.Close(); closeErr != nil {
			fmt.Fprintf(os.Stderr, "Erro ao fechar response body: %v\n", closeErr)
		}
	}()

	if resp.StatusCode != http.StatusOK {
		return ReleaseInfo{}, fmt.Errorf("erro ao verificar versão: status %d", resp.StatusCode)
	}

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return ReleaseInfo{}, err
	}

	var releaseInfo ReleaseInfo
	if err := json.Unmarshal(body, &releaseInfo); err != nil {
		return ReleaseInfo{}, err
	}
	return releaseInfo, nil
}

FetchLatestReleaseImpl é a implementação injetável da consulta à release mais recente (o único seam de rede deste pacote; testes o substituem ou apontam CHATCLI_LATEST_VERSION_URL para um servidor de teste).

View Source
var GetBuildInfoImpl = func() (string, string, string) {
	version := Version
	commitHash := CommitHash
	buildDate := BuildDate

	if version == "dev" || version == "unknown" ||
		commitHash == "unknown" || buildDate == "unknown" {

		if info, ok := debug.ReadBuildInfo(); ok {

			if (version == "dev" || version == "unknown") && info.Main.Version != "" && info.Main.Version != "(devel)" {
				version = strings.TrimPrefix(info.Main.Version, "v")
			}

			if (commitHash == "unknown" || len(commitHash) < 7) && info.Main.Version != "" {
				parts := strings.Split(info.Main.Version, "-")
				if len(parts) >= 3 {
					possibleCommit := parts[len(parts)-1]
					if len(possibleCommit) >= 7 {
						commitHash = possibleCommit
					}
				}
			}

			for _, setting := range info.Settings {
				switch setting.Key {
				case "vcs.revision":
					if commitHash == "unknown" || len(commitHash) < 7 {
						hash := setting.Value
						if len(hash) > 12 {
							hash = hash[:12]
						}
						commitHash = hash
					}
				case "vcs.time":
					if buildDate == "unknown" {
						if t, err := time.Parse(time.RFC3339, setting.Value); err == nil {
							buildDate = t.Format("2006-01-02 15:04:05")
						} else {
							buildDate = setting.Value
						}
					}
				}
			}
		}
	}

	if buildDate == "unknown" {
		if execPath, err := os.Executable(); err == nil {
			if info, err := os.Stat(execPath); err == nil {
				modTime := info.ModTime()
				buildDate = modTime.Format("2006-01-02 15:04:05") + buildDateApproxSuffix
			}
		}
	}
	return version, commitHash, buildDate
}

GetBuildInfoImpl é a implementação injetável para GetBuildInfo (pode ser mocked)

Functions

func CheckLatestVersionWithContext added in v1.25.1

func CheckLatestVersionWithContext(ctx context.Context) (string, bool, error)

CheckLatestVersionWithContext responde apenas "qual é a última versão e preciso atualizar?", sem tocar em estado do pacote. Fluxos de exibição devem preferir GetReport, que também enriquece o build info.

func ExtractBaseVersion added in v1.25.1

func ExtractBaseVersion(version string) string

ExtractBaseVersion extrai a parte base da versão, sem prefixo 'v' e sem sufixos de desenvolvimento Exemplo: "v1.9.0-5-g1b6ecaa-dirty" -> "1.9.0"

func FormatVersionInfo

func FormatVersionInfo(info VersionInfo, latest string, hasUpdate bool, checkErr error) string

FormatVersionInfo retorna uma string formatada com as informações de versão

func GetBuildInfo

func GetBuildInfo() (string, string, string)

GetBuildInfo é o wrapper exportado

func NeedsUpdate added in v1.25.1

func NeedsUpdate(currentVersion, latestVersion string) bool

NeedsUpdate verifica semanticamente se a versão atual precisa ser atualizada.

func RefreshReleaseCacheIfStale added in v1.160.2

func RefreshReleaseCacheIfStale(ctx context.Context)

RefreshReleaseCacheIfStale renova o cache quando vencido/ausente, limitada por um deadline próprio sobre o ctx do chamador — desenhada para rodar em goroutine no boot sem segurar nada. O TTL aqui é só throttle de rede (≤1 consulta/dia à API do GitHub); a exibição usa o cache em qualquer idade. Respeita CHATCLI_DISABLE_VERSION_CHECK e nunca retorna erro: a próxima exibição simplesmente usa o que houver.

Types

type ReleaseInfo added in v1.97.0

type ReleaseInfo struct {
	TagName     string `json:"tag_name"`
	PublishedAt string `json:"published_at"`
	TargetHash  string `json:"target_commitish"`
	Body        string `json:"body"`
	HTMLURL     string `json:"html_url"`
}

ReleaseInfo contém informações detalhadas de uma release do GitHub

type ReleaseNote added in v1.172.0

type ReleaseNote struct {
	Section string
	Text    string
}

ReleaseNote é um item das notas de release já limpo para exibição em terminal: o texto do bullet e a seção (Features, Bug Fixes, …) a que pertence, quando o corpo da release a declara.

func ReleaseHighlights added in v1.172.0

func ReleaseHighlights(body string, limit int) (notes []ReleaseNote, more int)

ReleaseHighlights extrai do corpo markdown de uma release (formato release-please/changelog) os bullets prontos para exibição, limitados a limit itens. Retorna também quantos bullets ficaram de fora, para o chamador oferecer o link da release completa. Função pura; corpo vazio ou sem bullets devolve lista vazia.

type Report added in v1.160.1

type Report struct {
	Current     VersionInfo
	Latest      string
	NeedsUpdate bool
	CheckErr    error
	// Notes carrega o corpo (markdown) da release mais recente quando há
	// atualização disponível — alimenta a seção "novidades" do /version e do
	// /update sem nenhuma chamada extra (vem no mesmo payload da API).
	Notes string
	// ReleaseURL aponta para a página da release no GitHub (quando conhecida).
	ReleaseURL string
}

Report reúne tudo que uma exibição de versão precisa: o build info resolvido (enriquecido com metadados da release quando o build não tem carimbo de VCS) e o resultado da checagem de atualização. Construí-lo não tem efeitos colaterais no pacote nem exige ordem entre resolução e check.

func GetReport added in v1.160.1

func GetReport(ctx context.Context) Report

GetReport resolve o build info atual e consulta a release mais recente em uma única composição. Com a checagem desabilitada (CHATCLI_DISABLE_VERSION_CHECK) o relatório carrega apenas o build info, com Latest vazio e CheckErr nil — o mesmo contrato do check isolado. Não muta estado do pacote; o único efeito além do retorno é persistir, em best-effort, o cache em disco da release (ver cache.go) que alimenta o OfflineReport da tela de boas-vindas.

func OfflineReport added in v1.160.2

func OfflineReport() Report

OfflineReport monta o relatório só com dados locais: build info resolvido e, quando há cache da release (mesmo vencido — é o último dado conhecido), o mesmo enriquecimento de commit/data do GetReport — sem nenhuma chamada de rede. É o que a tela de boas-vindas usa para mostrar o hash de um build go install e o banner de atualização sem atrasar o boot.

func (Report) Format added in v1.160.1

func (r Report) Format() string

Format renderiza o relatório no formato canônico de exibição.

type VersionInfo

type VersionInfo struct {
	Version    string `json:"version"`
	CommitHash string `json:"commit_hash"`
	BuildDate  string `json:"build_date"`
}

Info retorna informações estruturadas sobre a versão atual

func GetCurrentVersion

func GetCurrentVersion() VersionInfo

GetCurrentVersion retorna as informações de versão atuais. Delega em GetBuildInfo (em vez de ler as globais cruas) para que builds sem ldflags — o caso `go install` — ainda apresentem a versão do módulo, o vcs.revision e a data aproximada do binário. Para exibir também o enriquecimento via GitHub release, use GetReport — que compõe tudo sem depender de ordem de chamadas nem de estado mutável do pacote.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL