OverviewFilesCommitsIssuesDocsReleasesPeers

pear-git / lib / cli / config.js

86 lines · javascript ref:
/**
 * pgh config management
 *
 * Config file: ~/.config/pear-git/pgh.json
 */

import fs from 'bare-fs'
import path from 'bare-path'
import os from 'bare-os'

const CONFIG_DIR = path.join(os.homedir(), '.config', 'pear-git')
const CONFIG_FILE = path.join(CONFIG_DIR, 'pgh.json')

const DEFAULTS = {
  server: 'http://localhost:5005',
  token: null,
  serverKey: null,
  defaultRepo: null,
  defaultNamespace: null
}

export function loadConfig () {
  try {
    const data = fs.readFileSync(CONFIG_FILE, 'utf-8')
    return { ...DEFAULTS, ...JSON.parse(data) }
  } catch {
    return { ...DEFAULTS }
  }
}

export function saveConfig (cfg) {
  try {
    fs.mkdirSync(CONFIG_DIR, { recursive: true })
  } catch {}
  fs.writeFileSync(CONFIG_FILE, JSON.stringify(cfg, null, 2) + '\n')
}

export function getServer (flags) {
  if (flags.server) return flags.server
  const cfg = loadConfig()
  return cfg.server || DEFAULTS.server
}

export function getToken (flags) {
  if (flags.token) return flags.token
  const cfg = loadConfig()
  return cfg.token || null
}

export function getRepo (flags) {
  if (flags.repo) return flags.repo
  const cfg = loadConfig()
  return cfg.defaultRepo || null
}

export function getNamespace (flags) {
  if (flags.namespace) return flags.namespace
  const cfg = loadConfig()
  return cfg.defaultNamespace || null
}

/**
 * Check if pgh has been set up.
 * Passes if device-identity.json exists OR a token is already configured
 * (backward compat for existing server-machine setups).
 */
export function hasDeviceIdentity () {
  // Check device-identity.json (client machines)
  const deviceFile = path.join(CONFIG_DIR, 'device-identity.json')
  try {
    fs.statSync(deviceFile)
    return true
  } catch {}
  // Existing setup with token (server machines that pre-date device-identity)
  const cfg = loadConfig()
  if (cfg.token) return true
  return false
}

export function getServerKey (flags) {
  if (flags['server-key']) return flags['server-key']
  if (flags.serverKey) return flags.serverKey
  const cfg = loadConfig()
  return cfg.serverKey || null
}