utils

package
v1.1.18 Latest Latest
Warning

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

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

Documentation

Index

Constants

View Source
const SHENMA_BASE_URL = "https://zgsm.sangfor.com/costrict"
View Source
const SHENMA_PUBLIC_KEY = `` /* 450-byte string literal not displayed */

Variables

View Source
var CostrictDir string = GetCostrictDir()

(default: %USERPROFILE%/.costrict on Windows, $HOME/.costrict on Linux)

Functions

func ApiPath

func ApiPath(pattern string, paras ...string) string

*

  • Build API path from template and path parameters

func BuildLoginURL added in v0.1.3

func BuildLoginURL(params *LoginParams, path string, ignores ...string) (string, error)

"/oidc-auth/api/v1/plugin/login/token" "/oidc-auth/api/v1/plugin/login" BuildLoginURL constructs the login URL with the given parameters @Summary Build login URL with optional parameter ignoring @Description Constructs a login URL using the provided parameters, optionally ignoring specified URL parameters @param params - Login parameters object containing all login configuration @param path - Path to append to the base URL (optional, defaults to "/login") @param ignores - String array of parameter names to exclude from the URL (optional) @returns Built login URL as string, or error if URL construction fails

func CalcFileMd5

func CalcFileMd5(fpath string) (uint64, string, error)

*

  • 获取文件信息(大小及MD5)

func CompareVersion

func CompareVersion(local, remote VersionNumber) int

*

  • 比较版本

func FormatDuration

func FormatDuration(layout string, startTime string, endTime string) (string, error)

*

  • Calculate time duration between two formatted times
  • Uses "2006-01-02 15:04:05" format if none specified

func GenKeyFiles

func GenKeyFiles(publicFile, privateFile string) error

*

  • 生成一对公私钥,保存到文件publicFile和privateFile中

func GenKeys

func GenKeys() (pubKey, priKey []byte)

*

  • 生成一对公私钥

func GetCostrictDir

func GetCostrictDir() string

*

  • Get costrict directory path
  • @returns {string} Returns costrict directory path

func Login added in v0.1.3

func Login(params *LoginParams, progress func() error) (string, error)

Login performs the complete login process: 1. Opens the browser with the login URL 2. Periodically polls the token endpoint until a valid token is received 3. Returns the access token or an error

func OpenBrowser added in v0.1.3

func OpenBrowser(url string) error

OpenBrowser opens the specified URL in the default browser

func PrintArray

func PrintArray(arr []interface{}, callback func(s interface{}) (*orderedmap.OrderedMap, error)) error

*

  • Print array of items using callback to format each item
  • @param arr array of items to print
  • @param callback function to convert item to ordered map
  • @return error if conversion or printing fails

func PrintFormat

func PrintFormat(dataList []*orderedmap.OrderedMap) error

*

  • Format and print ordered map data as table
  • @param dataList slice of ordered maps to display
  • @return error if data is empty or formatting fails

func PrintFormatByOrderMap

func PrintFormatByOrderMap(s interface{}) error

*

  • Print single struct as formatted table using ordered map
  • @param s struct to print
  • @return error if conversion or printing fails

func PrintYaml

func PrintYaml(s interface{}) error

*

  • Print data structure in YAML format
  • @param s data to print
  • @return error if YAML marshaling fails

func QuantityCompare

func QuantityCompare(lhs, rhs Quantity) (int, error)

*

  • Compare two resource quantities

func RsaDecrypt

func RsaDecrypt(priKey []byte, cipherText []byte) []byte

*

  • 使用私钥进行解密

func RsaEncrypt

func RsaEncrypt(pubKey []byte, msg []byte) []byte

*

  • 使用公钥进行加密

func SaveAuthConfig added in v0.1.3

func SaveAuthConfig(config AuthConfig) error

func Sign

func Sign(priKey []byte, msg []byte) ([]byte, error)

*

  • 使用私钥签名,priKey是私钥,msg是要签名的信息

func StructToOrderedMap

func StructToOrderedMap(s interface{}) (*orderedmap.OrderedMap, error)

*

  • Convert struct to ordered map
  • @param s struct to convert
  • @return *orderedmap.OrderedMap converted map
  • @return error if input is not struct type

func Time2Sec

func Time2Sec(time string) (uint32, error)

*

  • Convert time duration string to seconds

func VerifySign

func VerifySign(pubKey []byte, signText []byte, plainText []byte) error

*

  • 使用公钥pubKey和签名signText校验消息plainText的完整性

Types

type AuthConfig added in v0.1.3

type AuthConfig struct {
	ID          string `json:"id"`
	Name        string `json:"name"`
	AccessToken string `json:"access_token"`
	MachineID   string `json:"machine_id"`
	BaseUrl     string `json:"base_url"`
}

type JWTClaims added in v0.1.3

type JWTClaims struct {
	ID          string `json:"id,omitempty"`
	Name        string `json:"name,omitempty"`
	DisplayName string `json:"displayName,omitempty"`
	Email       string `json:"email,omitempty"`
}

JWTClaims represents the decoded JWT token claims

func DecodeJWT added in v0.1.3

func DecodeJWT(token string) (*JWTClaims, error)

DecodeJWT decodes a JWT token without verifying the signature @Summary Decode JWT token without verification @description - Splits the JWT token into its three parts - Decodes the payload (second part) from base64 - Returns the claims as a JWTClaims struct @param token - The JWT token to decode @returns JWTClaims object containing user information or error if decoding fails

type Json

type Json = map[string]interface{}

type KeyValues

type KeyValues = map[string]string

type LoginParams added in v0.1.3

type LoginParams struct {
	BaseURL       string `json:"base_url,omitempty"`
	MachineCode   string `json:"machine_code,omitempty"`
	PluginVersion string `json:"plugin_version,omitempty"`
	VSCodeVersion string `json:"vscode_version,omitempty"`
	State         string `json:"state,omitempty"`
	Provider      string `json:"provider,omitempty"`
	URIScheme     string `json:"uri_scheme,omitempty"`
}

LoginParams represents the parameters for building login URL

type PackageList

type PackageList struct {
	Packages []string `json:"packages"`
}

*

  • 云端可供下载的包列表

type PackageOverview added in v0.1.3

type PackageOverview struct {
	PackageName string                      `json:"packageName"` //包名称
	Platforms   []PlatformId                `json:"platforms"`   //包支持的平台列表
	Overviews   map[string]PlatformOverview `json:"overviews"`   //包总览
}

*

  • 包目录(软件包的系统,平台,版本目录)

type PackageType

type PackageType string

*

  • 包类型枚举
const (
	PackageTypeExec PackageType = "exec"
	PackageTypeConf PackageType = "conf"
	PackageTypeZip  PackageType = "zip"
)

type PackageVersion added in v0.1.3

type PackageVersion struct {
	PackageName  string        `json:"packageName"`           //包名字
	PackageType  PackageType   `json:"packageType"`           //包类型: exec/conf
	FileName     string        `json:"fileName"`              //被打包的文件的相对路径(相对.costrict目录,为空则安装到默认路径)
	Os           string        `json:"os"`                    //操作系统名:linux/windows
	Arch         string        `json:"arch"`                  //硬件架构
	Size         uint64        `json:"size"`                  //包文件大小
	Checksum     string        `json:"checksum"`              //Md5散列值
	Sign         string        `json:"sign"`                  //签名,使用私钥签的名,需要用对应公钥验证
	ChecksumAlgo string        `json:"checksumAlgo"`          //固定为“md5”
	VersionId    VersionNumber `json:"versionId"`             //版本号,采用SemVer标准
	Build        string        `json:"build"`                 //构建信息:Tag/Branch信息 CommitID BuildTime
	ReleaseTime  string        `json:"releaseTime,omitempty"` //包发布时间
	Description  string        `json:"description"`           //版本描述,含有更丰富的可读信息
}

*

  • 包版本的描述&签名信息,用于验证包的正确性

func (*PackageVersion) Load added in v0.1.3

func (pkg *PackageVersion) Load(fname string) error

func (*PackageVersion) Save added in v0.1.3

func (pkg *PackageVersion) Save(fname string) error

func (*PackageVersion) Verify added in v0.1.3

func (pkg *PackageVersion) Verify() error

type PlatformId

type PlatformId struct {
	Os   string `json:"os"`
	Arch string `json:"arch"`
}

*

  • 平台标识

type PlatformInfo

type PlatformInfo struct {
	PackageName string        `json:"packageName"`
	Os          string        `json:"os"`
	Arch        string        `json:"arch"`
	Newest      VersionAddr   `json:"newest"`
	Versions    []VersionAddr `json:"versions"`
}

*

  • 指定平台的关键信息,比如,最新版本,版本列表(描述一个硬件平台/操作系统对应的包列表)

type PlatformOverview added in v0.1.3

type PlatformOverview struct {
	Os       string            `json:"os"`
	Arch     string            `json:"arch"`
	Newest   VersionOverview   `json:"newest"`
	Versions []VersionOverview `json:"versions"`
}

type Quantity

type Quantity struct {
	Amend int64  // Integer value
	Unit  string // Unit
}

func NewQuantity

func NewQuantity(amend int64, unit string) (Quantity, error)

*

  • Create new resource quantity object

func QuantityMinus

func QuantityMinus(lhs, rhs Quantity) (Quantity, error)

*

  • Subtract two resource quantities

func QuantityParse

func QuantityParse(qstr string) (Quantity, error)

*

  • Parse resource quantity from string

func QuantityPlus

func QuantityPlus(lhs, rhs Quantity) (Quantity, error)

*

  • Add two resource quantities

func (*Quantity) ChangeUnit

func (q *Quantity) ChangeUnit(unit string) error

*

  • Change display unit of resource quantity

func (*Quantity) K8sString

func (q *Quantity) K8sString() string

*

  • Kubernetes-style representation, e.g: 1Ki, 1Mi

func (*Quantity) Minus

func (q *Quantity) Minus(rhs Quantity) error

*

  • Decrease resource quantity

func (*Quantity) Optimize

func (q *Quantity) Optimize() Quantity

*

  • Optimize for better display

func (*Quantity) Parse

func (q *Quantity) Parse(num string) error

*

  • Parse resource quantity from string representation

func (*Quantity) Plus

func (q *Quantity) Plus(rhs Quantity) error

*

  • Increase resource quantity

func (*Quantity) String

func (q *Quantity) String() string

*

  • String representation, e.g: 100m,1K,1000

type RespData

type RespData struct {
	Code    string      `json:"code"`
	Message string      `json:"message,omitempty"`
	Success bool        `json:"success"`
	Data    interface{} `json:"data,omitempty"`
}

type Scale

type Scale struct {
	Unit     string
	Multiple int64
}

*

  • Scaling parameters for measurement units

type Session

type Session struct {
	HostUrl string `json:"url"`
	// contains filtered or unexported fields
}

*

  • HTTP Session

func NewProxySession

func NewProxySession(hostUrl, proxy string) *Session

*

  • Create new Session using proxy

func NewSession

func NewSession(url string) *Session

*

  • Create new Session for communicating with AI platform

func (*Session) Delete

func (ss *Session) Delete(apiPath string) ([]byte, error)

*

  • Send raw DELETE request

func (*Session) DeleteJson

func (ss *Session) DeleteJson(apiPath string, data Json) ([]byte, error)

*

  • Send raw DELETE request

func (*Session) Get

func (ss *Session) Get(apiPath string, params Json) ([]byte, error)

*

  • Send GET request

func (*Session) GetBody

func (ss *Session) GetBody(apiPath string, params Json) (io.ReadCloser, error)

*

  • Send GET request

func (*Session) GetData

func (ss *Session) GetData(apiPath string, params Json) ([]byte, error)

*

  • Get JSON data from AIP

func (*Session) Post

func (ss *Session) Post(apiPath string, body []byte) ([]byte, error)

*

  • Send raw POST request

func (*Session) PostJson

func (ss *Session) PostJson(apiPath string, jsonData Json) ([]byte, error)

*

  • POST data to AIP

func (*Session) Put

func (ss *Session) Put(apiPath string, data Json) ([]byte, error)

*

  • Send raw PUT request

func (*Session) Request

func (ss *Session) Request(method, apiPath string, paths, querys, headers map[string]string, body []byte) ([]byte, error)

type TokenResponse added in v0.1.3

type TokenResponse struct {
	Code int `json:"code,omitempty"`
	Data struct {
		AccessToken  string `json:"access_token,omitempty"`
		RefreshToken string `json:"refresh_token,omitempty"`
		State        string `json:"state,omitempty"`
	} `json:"data,omitempty"`
	Message string `json:"message,omitempty"`
	Success bool   `json:"success,omitempty"`
}

TokenResponse represents the response from the token endpoint

func GetToken added in v0.1.3

func GetToken(params *LoginParams) (*TokenResponse, error)

GetToken sends a GET request to the token endpoint with the same parameters used for login @Summary Get authentication token from token endpoint @Description Sends a GET request to the token endpoint with login parameters @param params - Login parameters object containing all login configuration @returns TokenResponse object containing authentication token or error, or error if request fails

type UpgradeConfig

type UpgradeConfig struct {
	PublicKey  string //用来验证包签名的公钥
	BaseUrl    string //保存安装包的服务器的基地址
	BaseDir    string //costrict数据所在的基路径
	Os         string //操作系统名
	Arch       string //硬件平台名
	TargetPath string //指定安装目标路径(及文件名)
	NoSetPath  bool   //不需要设置PATH。设置PATH可以让程序所在路径被自动搜索
	VerifyTLS  bool   //进行TLS/SSL相关的安全校验
}

type Upgrader added in v0.1.3

type Upgrader struct {
	UpgradeConfig
	// contains filtered or unexported fields
}

func NewUpgrader added in v0.1.3

func NewUpgrader(packageName string, cfg UpgradeConfig, client *http.Client) *Upgrader

func (*Upgrader) ActivatePackage added in v0.1.3

func (u *Upgrader) ActivatePackage(pkg PackageVersion) error

*

  • 激活版本ver的包,令其成为当前版本

func (*Upgrader) AddPinned added in v0.1.3

func (u *Upgrader) AddPinned(pkg PackageVersion) error

*

  • 固定版本,令自动升级忽略该包

func (*Upgrader) AddTodo added in v0.1.3

func (u *Upgrader) AddTodo(pkg PackageVersion) error

func (*Upgrader) CleanupOlders added in v0.1.3

func (u *Upgrader) CleanupOlders(reserveNum int) error

*

  • 清理package目录下过老的版本包数据
  • @param {string} baseDir - costrict数据所在的基路径,如果为空则使用默认路径
  • @returns {error} 返回错误对象,成功时返回nil
  • @description
  • - 扫描版本描述文件package/x-{ver}.json文件,提取文件中保存的版本信息
  • - 保证每个模块只保留最新的三个包,过老的包需要清除
  • - 删除过老的包描述文件x-{ver}.json和package/{ver}/{targetFile}
  • - 支持自定义baseDir,如果为空则使用默认的.costrict目录
  • - 按包名分组处理,每个包保留最新的三个版本
  • @throws
  • - 读取package目录失败
  • - 解析版本描述文件失败
  • - 删除包文件或描述文件失败

func (*Upgrader) CleanupPackage added in v0.1.3

func (u *Upgrader) CleanupPackage(reserveNum int)

*

  • 清理包缓存中太老的版本包

func (*Upgrader) Close added in v0.1.3

func (u *Upgrader) Close() error

*

  • Close the HTTP client and clean up resources
  • @returns {error} Returns error if closing fails, nil on success
  • @description
  • - Closes idle HTTP connections to prevent resource leaks
  • - Should be called when the Upgrader is no longer needed
  • - Safe to call multiple times
  • @example
  • upgrader := NewUpgrader("mypkg", config)
  • defer upgrader.Close()

func (*Upgrader) GetBytes added in v0.1.3

func (u *Upgrader) GetBytes(urlStr string, params map[string]string) ([]byte, error)

*

  • 从云端获取一个文件的内容

func (*Upgrader) GetFile added in v0.1.3

func (u *Upgrader) GetFile(urlStr string, params map[string]string, savePath string) error

*

  • 从服务器获取一个文件

func (*Upgrader) GetInstallPaths added in v0.1.3

func (u *Upgrader) GetInstallPaths(pkg *PackageVersion) (dir, fname, fullpath string)

func (*Upgrader) GetLocalVersion added in v0.1.3

func (u *Upgrader) GetLocalVersion(ver *VersionNumber) (pkg PackageVersion, err error)

*

  • 获取本地包信息
  • 如果指定了版本,则获取指定版本包信息,否则获取最新版本

func (*Upgrader) GetPackage added in v0.1.3

func (u *Upgrader) GetPackage(specVer *VersionNumber) (PackageVersion, bool, error)

*

  • 获取包(需要校验保证包的合法性)

func (*Upgrader) GetPinned added in v0.1.3

func (u *Upgrader) GetPinned() (pkg PackageVersion, err error)

func (*Upgrader) GetRemotePackages added in v0.1.3

func (u *Upgrader) GetRemotePackages() (PackageList, error)

func (*Upgrader) GetRemotePlatforms added in v0.1.3

func (u *Upgrader) GetRemotePlatforms() (PackageOverview, error)

func (*Upgrader) GetRemoteVersions added in v0.1.3

func (u *Upgrader) GetRemoteVersions() (PlatformInfo, error)

*

  • 从远程库获取包版本
  • 如果具体的os/arch不存在,则尝试获取common/common的通用包

func (*Upgrader) GetTodo added in v0.1.3

func (u *Upgrader) GetTodo() (pkg PackageVersion, err error)

func (*Upgrader) RemovePackage added in v0.1.3

func (u *Upgrader) RemovePackage(ver *VersionNumber) error

*

  • 移除指定版本或当前版本的包

func (*Upgrader) RemovePinned added in v0.1.3

func (u *Upgrader) RemovePinned()

func (*Upgrader) RemoveTodo added in v0.1.3

func (u *Upgrader) RemoveTodo()

func (*Upgrader) SyncPackage added in v0.1.3

func (u *Upgrader) SyncPackage(dstDir string) error

*

  • SyncPackage 将远程包目录树以镜像的方式同步到本地目录
  • 下载层次结构:
  • - dstDir/platforms.json ← <base-url>/<package>/platforms.json
  • - 对于每个平台组合 (os/arch):
  • - dstDir/<os>/<arch>/platform.json ← <base-url>/<package>/<os>/<arch>/platform.json
  • - 对于每个版本:
  • - dstDir/<os>/<arch>/<version>/package.json ← <base-url>/<package>/<os>/<arch>/<version>/package.json
  • - dstDir/<os>/<arch>/<version>/ ← <base-url>/<package>/<os>/<arch>/<version>/<filename>

func (*Upgrader) UpgradePackage added in v0.1.3

func (u *Upgrader) UpgradePackage(specVer *VersionNumber) (PackageVersion, bool, error)

*

  • 升级包

type VersionAddr

type VersionAddr struct {
	VersionId VersionNumber `json:"versionId"` //版本的地址信息
	AppUrl    string        `json:"appUrl"`    //包地址
	InfoUrl   string        `json:"infoUrl"`   //包描述信息(PackageVersion)文件的地址
}

*

  • 一个package版本的地址信息

type VersionNumber

type VersionNumber struct {
	Major int `json:"major"`
	Minor int `json:"minor"`
	Micro int `json:"micro"`
}

*

  • 版本编号

func NewVersion added in v0.1.3

func NewVersion(verStr string) (v VersionNumber, err error)

------------------------------------------------------------------------------

VersionNumber

------------------------------------------------------------------------------

func (*VersionNumber) Parse added in v0.1.3

func (ver *VersionNumber) Parse(verstr string) error

func (*VersionNumber) String added in v0.1.3

func (ver *VersionNumber) String() string

type VersionOverview added in v0.1.3

type VersionOverview struct {
	VersionId   VersionNumber `json:"versionId"`   //版本号,采用SemVer标准
	PackageType PackageType   `json:"packageType"` //包类型: exec/conf
	FileName    string        `json:"fileName"`    //被打包的文件的名字
	Size        uint64        `json:"size"`        //包文件大小
	ReleaseTime string        `json:"releaseTime"` //发布时间
	Build       string        `json:"build"`       //构建信息:Tag/Branch信息 CommitID BuildTime
	Description string        `json:"description"` //版本描述,含有更丰富的可读信息
}

Jump to

Keyboard shortcuts

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