himidori / go-hwinfo-parser

GNU General Public License v3.0
1 stars 1 forks source link

Your code did not running in sudo access. I have change your code and attached below #2

Open anandharaj-dotworld opened 2 years ago

anandharaj-dotworld commented 2 years ago
package main

import (
    "fmt"
    "log"
    "os/exec"
    "reflect"
    "regexp"
    "strconv"
    "strings"
)

const (
    endDebugPattern = `=*\send debug info\s=*`
    titlePattern    = `\d{2}:\s.+`
)

type HardwareInfo struct {
    BIOS                     BIOS                      `json:"bios"`
    System                   System                    `json:"system"`
    MainMemory               MainMemory                `json:"mainMemory"`
    FPUS                     []FPU                     `json:"fpus"`
    DMAControllers           []DMAController           `json:"dmaControllers"`
    PICS                     []PIC                     `json:"pics"`
    KeyboardControllers      []KeyboardController      `json:"keyboardControllers"`
    WLANControllers          []WLANController          `json:"wlanControllers"`
    SATAControllers          []SATAController          `json:"sataControllers"`
    PCIBridges               []PCIBridge               `json:"pciBridges"`
    ISABridges               []ISABridge               `json:"isaBridges"`
    CommunicationControllers []CommunicationController `json:"communicationControllers"`
    AudioDevices             []AudioDevice             `json:"audioDevices"`
    EthernetControllers      []EthernetController      `json:"ethernetControllers"`
    SMBuses                  []SMBus                   `json:"smBuses"`
    HostBridges              []HostBridge              `json:"hostBridges"`
    USBControllers           []USBController           `json:"usbControllers"`
    SerialControllers        []SerialController        `json:"serialControllers"`
    SystemPeripherals        []SystemPeripheral        `json:"systemPeripherals"`
    VGACompatibleControllers []VGACompatibleController `json:"vgaCompatibleControllers"`
    LCDMonitors              []LCDMonitor              `json:"lcdMonitors"`
    Disks                    []Disk                    `json:"disks"`
    Partitions               []Partition               `json:"partitions"`
    BluetoothDevices         []BluetoothDevice         `json:"bluetoothDevices"`
    UnclassifiedDevices      []UnclassifiedDevice      `json:"unclassifiedDevices"`
    Hubs                     []Hub                     `json:"hubs"`
    Keyboards                []Keyboard                `json:"keyboards"`
    USBMouses                []USBMouse                `json:"usbMouses"`
    CPUS                     []CPU                     `json:"cpus"`
    Loopbacks                []Loopback                `json:"loopbacks"`
    Ethernets                []Ethernet                `json:"ethernets"`
}

type BIOS struct {
    UniqueID      string `json:"uniqueId"`
    HardwareClass string `json:"hardwareClass"`
    ConfigStatus  string `json:"configStatus"`
}

type System struct {
    UniqueID      string `json:"uniqueId"`
    HardwareClass string `json:"hardwareClass"`
    Model         string `json:"model"`
    Formfactor    string `json:"formFactor"`
    ConfigStatus  string `json:"configStatus"`
}

type FPU struct {
    UniqueID      string   `json:"uniqueId"`
    HardwareClass string   `json:"hardwareClass"`
    Model         string   `json:"model"`
    IOPort        []string `json:"ioports"`
    ConfigStatus  string   `json:"configStatus"`
}

type DMAController struct {
    UniqueID      string   `json:"uniqueId"`
    HardwareClass string   `json:"hardwareClass"`
    Model         string   `json:"model"`
    IOPort        []string `json:"ioports"`
    DMA           int64    `json:"dma"`
    ConfigStatus  string   `json:"configStatus"`
}

type PIC struct {
    UniqueID      string   `json:"uniqueId"`
    HardwareClass string   `json:"hardwareClass"`
    Model         string   `json:"model"`
    IOPort        []string `json:"ioports"`
    ConfigStatus  string   `json:"configStatus"`
}

type KeyboardController struct {
    UniqueID      string   `json:"uniqueId"`
    HardwareClass string   `json:"hardwareClass"`
    Model         string   `json:"model"`
    IOPort        []string `json:"ioports"`
    ConfigStatus  string   `json:"configStatus"`
}

type MainMemory struct {
    UniqueID      string `json:"uniqueId"`
    HardwareClass string `json:"hardwareClass"`
    Model         string `json:"model"`
    MemoryRange   string `json:"memoryRange"`
    MemorySize    string `json:"memorySize"`
    ConfigStatus  string `json:"configStatus"`
}

type WLANController struct {
    UniqueID                string `json:"uniqueId"`
    ParentID                string `json:"parentId"`
    SysFSID                 string `json:"sysFsId"`
    SysFSBusID              string `json:"sysFsBusId"`
    HardwareClass           string `json:"hardwareClass"`
    Model                   string `json:"model"`
    Vendor                  string `json:"vendor"`
    Device                  string `json:"device"`
    SubVendor               string `json:"subVendor"`
    SubDevice               string `json:"subDevice"`
    Revision                string `json:"revision"`
    Driver                  string `json:"driver"`
    DriverModules           string `json:"driverModules"`
    DeviceFile              string `json:"deviceFile"`
    Features                string `json:"features"`
    MemoryRange             string `json:"memoryRange"`
    IRQ                     string `json:"irq"`
    HWAddress               string `json:"hwAddress"`
    PermanentHWAddress      string `json:"permanentHwAddress"`
    LinkDetected            string `json:"linkDetected"`
    WLANChannels            string `json:"wlanChannels"`
    WLANFrequences          string `json:"wlanFrequences"`
    WLANEncryptionModes     string `json:"wlanEncryptionModes"`
    WLANAuthenticationModes string `json:"wlanAuthenticationModes"`
    ModuleAlias             string `json:"moduleAlias"`
    ConfigStatus            string `json:"configStatus"`
    AttachedTo              string `json:"attachedTo"`
}

type SATAController struct {
    UniqueID      string   `json:"uniqueId"`
    SysFSID       string   `json:"sysFsId"`
    SysFSBusID    string   `json:"sysFsBusId"`
    HardwareClass string   `json:"hardwareClass"`
    Model         string   `json:"model"`
    Vendor        string   `json:"vendor"`
    Device        string   `json:"device"`
    SubVendor     string   `json:"subVendor"`
    SubDevice     string   `json:"subDevice"`
    Revision      string   `json:"revision"`
    Driver        string   `json:"driver"`
    DriverModules string   `json:"driverModules"`
    MemoryRange   []string `json:"memoryRanges"`
    IOPort        []string `json:"ioPorts"`
    IRQ           string   `json:"irq"`
    ModuleAlias   string   `json:"moduleAlias"`
    ConfigStatus  string   `json:'configStatus`
}

type MemoryController struct {
    UniqueID      string   `json:"uniqueId"`
    SysFSID       string   `json:"sysFsId"`
    SysFSBusID    string   `json:"sysFsBusId"`
    HardwareClass string   `json:"hardwareClass"`
    Model         string   `json:"model"`
    Vendor        string   `json:"vendor"`
    Device        string   `json:"device"`
    SubVendor     string   `json:"subVendor"`
    SubDevice     string   `json:"subDevice"`
    Revision      string   `json:"revision"`
    MemoryRange   []string `json:"memoryRanges"`
    ModuleAlias   string   `json:"moduleAlias"`
    ConfigStatus  string   `json:"configStatus"`
}

type Bridge struct {
    UniqueID      string `json:"uniqueId"`
    SysFSID       string `json:"sysFsId"`
    SysFSBusID    string `json:"sysFsBusId"`
    HardwareClass string `json:"hardwareClass"`
    Model         string `json:"model"`
    Vendor        string `json:"vendor"`
    Device        string `json:"device"`
    SubVendor     string `json:"subVendor"`
    SubDevice     string `json:"subDevice"`
    Revision      string `json:"revision"`
    Driver        string `json:"driver"`
    IRQ           string `json:"irq"`
    ModuleAlias   string `json:"moduleAlias"`
    ConfigStatus  string `json:"configStatus"`
}

type ISABridge struct {
    UniqueID      string `json:"uniqueId"`
    SysFSID       string `json:"sysFsId"`
    SysFSBusID    string `json:"sysFsBusId"`
    HardwareClass string `json:"hardwareClass"`
    Model         string `json:"model"`
    Vendor        string `json:"vendor"`
    Device        string `json:"device"`
    SubVendor     string `json:"subVendor"`
    SubDevice     string `json:"subDevice"`
    Revision      string `json:"revision"`
    Driver        string `json:"driver"`
    DriverModules string `json:"driverModules"`
    ModuleAlias   string `json:"moduleAlias"`
    ConfigStatus  string `json:"configStatus"`
}

type CommunicationController struct {
    UniqueID      string   `json:"uniqueId"`
    SysFSID       string   `json:"sysFsId"`
    SysFSBusID    string   `json:"sysFsBusId"`
    HardwareClass string   `json:"hardwareClass"`
    Model         string   `json:"model"`
    Vendor        string   `json:"vendor"`
    Device        string   `json:"device"`
    SubVendor     string   `json:"subVendor"`
    SubDevice     string   `json:"subDevice"`
    Revision      string   `json:"revision"`
    Driver        string   `json:"driver"`
    DriverModules string   `json:"driverModules"`
    MemoryRange   []string `json:"memoryRanges"`
    IRQ           string   `json:"irq"`
    ModuleAlias   string   `json:"moduleAlias"`
    ConfigStatus  string   `json:"configStatus"`
}

type AudioDevice struct {
    UniqueID      string   `json:"uniqueId"`
    SysFSID       string   `json:"sysFsId"`
    SysFSBusID    string   `json:"sysFsBusId"`
    HardwareClass string   `json:"hardwareClass"`
    Model         string   `json:"model"`
    Vendor        string   `json:"vendor"`
    Device        string   `json:"device"`
    SubVendor     string   `json:"subVendor"`
    SubDevice     string   `json:"subDevice"`
    Revision      string   `json:"revision"`
    Driver        string   `json:"driver"`
    DriverModules string   `json:"driverModules"`
    MemoryRange   []string `json:"memoryRanges"`
    IRQ           string   `json:"irq"`
    ModuleAlias   string   `json:"moduleAlias"`
    ConfigStatus  string   `json:"configStatus"`
}

type PCIBridge struct {
    UniqueID      string `json:"uniqueId"`
    SysFSID       string `json:"sysFsId"`
    SysFSBusID    string `json:"sysFsBusId"`
    HardwareClass string `json:"hardwareClass"`
    Model         string `json:"model"`
    Vendor        string `json:"vendor"`
    Device        string `json:"device"`
    SubVendor     string `json:"subVendor"`
    SubDevice     string `json:"subDevice"`
    Revision      string `json:"revision"`
    Driver        string `json:"driver"`
    IRQ           string `json:"irq"`
    ModuleAlias   string `json:"moduleAlias"`
    ConfigStatus  string `json:"configStatus"`
}

type EthernetController struct {
    UniqueID           string   `json:"uniqueId"`
    SysFSID            string   `json:"sysFsId"`
    SysFSBusID         string   `json:"sysFsBusId"`
    HardwareClass      string   `json:"hardwareClass"`
    Model              string   `json:"model"`
    Vendor             string   `json:"vendor"`
    Device             string   `json:"device"`
    SubVendor          string   `json:"subVendor"`
    SubDevice          string   `json:"subDevice"`
    Revision           string   `json:"revision"`
    Driver             string   `json:"driver"`
    DriverModules      string   `json:"driverModules"`
    DeviceFile         string   `json:"deviceFile"`
    MemoryRange        []string `json:"memoryRanges"`
    IRQ                string   `json:"irq"`
    HWAddress          string   `json:"hwAddress"`
    PermanentHWAddress string   `json:"permanentHwAddress"`
    LinkDetected       string   `json:"linkDetected"`
    ModuleAlias        string   `json:"moduleAlias"`
    ConfigStatus       string   `json:"configStatus"`
}

type SMBus struct {
    UniqueID      string   `json:"smBus"`
    SysFSID       string   `json:"sysFsId"`
    SysFSBusID    string   `json:"sysFsBusId"`
    HardwareClass string   `json:"hardwareClass"`
    Model         string   `json:"model"`
    Vendor        string   `json:"vendor"`
    Device        string   `json:"device"`
    SubVendor     string   `json:"subVendor"`
    SubDevice     string   `json:"subDevice"`
    Revision      string   `json:"revision"`
    Driver        string   `json:"driver"`
    DriverModules string   `json:"driverModules"`
    MemoryRange   []string `json:"memoryRanges"`
    IRQ           string   `json:"irq"`
    ModuleAlias   string   `json:"moduleAlias"`
    ConfigStatus  string   `json:"configStatus"`
}

type HostBridge struct {
    UniqueID      string `json:"uniqueId"`
    SysFSID       string `json:"sysFsId"`
    SysFSBusID    string `json"sysFsBusId"`
    HardwareClass string `json:"hardwareClass"`
    Model         string `json:"model"`
    Vendor        string `json:"vendor"`
    Device        string `json:"device"`
    SubVendor     string `json:"subVendor"`
    SubDevice     string `json:"subDevice"`
    Revision      string `json:"revision"`
    ModuleAlias   string `json:"moduleaLias"`
    ConfigStatus  string `json:"configStatus"`
}

type USBController struct {
    UniqueID      string   `json:"uniqueId"`
    SysFSID       string   `json:"sysFsId"`
    SysFSBusID    string   `json:"sysFsBusId"`
    HardwareClass string   `json:"hardwareClass"`
    Model         string   `json:"model"`
    Vendor        string   `json:"vendor"`
    Device        string   `json:"device"`
    SubVendor     string   `json:"subVendor"`
    SubDevice     string   `json:"subDevice"`
    Revision      string   `json:"revision"`
    Driver        string   `json:"driver"`
    DriverModules string   `json:"driverModules"`
    MemoryRange   []string `json:"memoryRanges"`
    IRQ           string   `json:"irq"`
    ModuleAlias   string   `json:"moduleAlias"`
    ConfigStatus  string   `json:"configStatus"`
}

type SerialController struct {
    UniqueID      string `json:"uniqueId"`
    SysFSID       string `json:"sysFsId"`
    SysFSBusID    string `json:"sysFsBusId"`
    HardwareClass string `json:"hardwareClass"`
    Model         string `json:"model"`
    Vendor        string `json:"vendor"`
    Device        string `json:"device"`
    SubVendor     string `json:"subVendor"`
    SubDevice     string `json:"subDevice"`
    Revision      string `json:"revision"`
    Driver        string `json:"driver"`
    MemoryRange   string `json:"memoryRange"`
    IRQ           string `json:"irq"`
    ModuleAlias   string `json:"moduleAlias"`
    ConfigStatus  string `json:"configStatus"`
}

type SystemPeripheral struct {
    UniqueID      string `json:"uniqueId"`
    ParentID      string `json:"parentId"`
    SysFSID       string `json:"sysFsId"`
    SysFSBusID    string `json:"sysFsBusId"`
    HardwareClass string `json:"hardwareClass"`
    Model         string `json:"model"`
    Vendor        string `json:"vendor"`
    Device        string `json:"device"`
    SubVendor     string `json:"subVendor"`
    SubDevice     string `json:"subDevice"`
    Revison       string `json:"revision"`
    Driver        string `json:"driver"`
    DriverModules string `json:"driverModules"`
    MemoryRange   string `json:"memoryRange"`
    IRQ           string `json:"irq"`
    ModuleAlias   string `json:"moduleAlias"`
    ConfigStatus  string `json:"configStatus"`
}

type VGACompatibleController struct {
    UniqueID      string   `json:"uniqueId"`
    SysFSID       string   `json:"sysFsId"`
    SysFSBusID    string   `json:"sysFsBusId"`
    HardwareClass string   `json:"hardwareClass"`
    Model         string   `json:"model"`
    Vendor        string   `json:"vendor"`
    Device        string   `json:"device"`
    SubVendor     string   `json:"subVendor"`
    SubDevice     string   `json:"subDevice"`
    Revision      string   `json:"revision"`
    Driver        string   `json:"driver"`
    DriverModules string   `json:"driverModules"`
    MemoryRange   []string `json:"memoryRanges"`
    IRQ           string   `json:"irq"`
    ModuleAlias   string   `json:"moduleAlias"`
    ConfigStatus  string   `json:"configStatus"`
}

type LCDMonitor struct {
    UniqueID          string   `json:"uniqueId"`
    ParentID          string   `json:"parentId"`
    HardwareClass     string   `json:"hardwareClass"`
    Model             string   `json:"model"`
    Vendor            string   `json:"vendor"`
    Device            string   `json:"device"`
    Resolution        []string `json:"resolutions"`
    Size              string   `json:"size"`
    YearOfManufacture int64    `json:"yearOfManufacture"`
    WeekOfManufacture int64    `json:"weekOfManufacture"`
    ConfigStatus      string   `json:"configStatus"`
    AttachedTo        string   `json:"attachedTo"`
}

type Disk struct {
    UniqueID        string `json:"uniqueId"`
    ParentID        string `json:"parentId"`
    SysFSID         string `json:"sysFsId"`
    SysFSBusID      string `json:"sysFsBusId"`
    SysFSDeviceLink string `json:"sysFsDeviceLink"`
    HardwareClass   string `json:"hardwareClass"`
    Model           string `json:"model"`
    Vendor          string `json:"vendor"`
    Device          string `json:"device"`
    Revision        string `json:"revision"`
    Driver          string `json:"driver"`
    DriverModules   string `json:"driverModules"`
    DeviceFile      string `json:"deviceFile"`
    DeviceFiles     string `json:"deviceFiles"`
    DeviceNumber    string `json:"deviceNumber"`
    BIOSID          string `json:"biosId"`
    DriveStatus     string `json:"driveStatus"`
    ConfigStatus    string `json:"configStatus"`
    AttachedTo      string `json:"attachedTo"`
}

type Partition struct {
    UniqueID      string `json:"uniqueId"`
    ParentID      string `json:"parentId"`
    SysFSID       string `json:"sysFsId"`
    HardwareClass string `json:"hardwareClass"`
    Model         string `json:"model"`
    DeviceFile    string `json:"deviceFile"`
    DeviceFiles   string `json:"deviceFiles"`
    ConfigStatus  string `json:"configStatus"`
    AttachedTo    string `json:"attachedTo"`
}

type BluetoothDevice struct {
    UniqueID      string `json:"uniqueId"`
    ParentID      string `json:"parentId"`
    SysFSID       string `json:"sysFsId"`
    SysFSBusID    string `json:"sysFsBusId"`
    HardwareClass string `json:"hardwareClass"`
    Model         string `json:"model"`
    Hotplug       string `json:"hotplug"`
    Vendor        string `json:"vendor"`
    Device        string `json:"device"`
    Revision      string `json:"revision"`
    SerialID      string `json:"serialId"`
    Speed         string `json:"speed"`
    ModuleAlias   string `json:"moduleAlias"`
    ConfigStatus  string `json:"configStatus"`
    AttachedTo    string `json:"attachedTo"`
}

type UnclassifiedDevice struct {
    UniqueID      string `json:"uniqueId"`
    ParentID      string `json:"parentId"`
    SysFSID       string `json:"sysFsId"`
    SysFSBusID    string `json:"sysFsBusId"`
    HardwareClass string `json:"hardwareClassa"`
    Model         string `json"model"`
    Hotplug       string `json:"hotplug"`
    Vendor        string `json:"vendor"`
    Device        string `json:"device"`
    Revision      string `json:"revision"`
    Driver        string `json:"driver"`
    DriverModules string `json:"driverModules"`
    Speed         string `json:"speed"`
    ModuleAlias   string `json:"moduleAlias"`
    ConfigStatus  string `json:"configStatus"`
    AttachedTo    string `json:"attachedTo"`
}

type Hub struct {
    UniqueID      string `json:"uniqueId"`
    ParentID      string `json:"parentId"`
    SysFSID       string `json:"sysFsId"`
    SysFSBusID    string `json:"sysFsBusId"`
    HardwareClass string `json:"hardwareClass"`
    Model         string `json:"model"`
    Hotplug       string `json:"hotplug"`
    Vendor        string `json:"vendor"`
    Device        string `json:"device"`
    Driver        string `json:"driver"`
    DriverModules string `json:"driverModules"`
    Speed         string `json:"speed"`
    ModuleAlias   string `json:"moduleAlias"`
    ConfigStatus  string `json:"configStatus"`
    AttachedTo    string `json:"attachedTo"`
}

type Keyboard struct {
    UniqueID      string `json:"uniqueId"`
    ParentID      string `json:"parentId"`
    SysFSID       string `json:"sysFsId"`
    SysFSBusID    string `json:"sysFsBusId"`
    HardwareClass string `json:"hardwareClass"`
    Model         string `json:"model"`
    Hotplug       string `json:"hotplug"`
    Vendor        string `json:"vendor"`
    Device        string `json:"device"`
    Revision      string `json:"revision"`
    Driver        string `json:"driver"`
    DriverModules string `json:"driverModules"`
    CompatibleTo  string `json:"compatibleTo"`
    DeviceFile    string `json:"deviceFile"`
    DeviceFiles   string `json:"deviceFiles"`
    DeviceNumber  string `json:"deviceNumber"`
    Speed         string `json:"speed"`
    ConfigStatus  string `json:"configStatus"`
    AttachedTo    string `json:"attachedTo"`
}

type USBMouse struct {
    UniqueID      string `json:"uniqueId"`
    HardwareClass string `json:"hardwareClass"`
    Model         string `json:"model"`
    Vendor        string `json:"vendor"`
    Device        string `json:"device"`
    CompatibleTo  string `json:"compatibleTo"`
    DeviceFile    string `json:"deviceFile"`
    DeviceFiles   string `json:"deviceFiles"`
    DeviceNumber  string `json:"deviceNumber"`
    ConfigStatus  string `json:"configStatus"`
}

type CPU struct {
    UniqueID      string `json:"uniqueId"`
    HardwareClass string `json:"hardwareClass"`
    Arch          string `json:"arch"`
    Vendor        string `json:"vendor"`
    Model         string `json:"model"`
    Features      string `json:"features"`
    Clock         string `json:"clock"`
    BogoMips      string `json:"bogoMips"`
    Cache         string `json:"cache"`
    ConfigStatus  string `json:"configStatus"`
}

type Loopback struct {
    UniqueID      string `json:"uniqueId"`
    SysFSID       string `json:"sysFsId"`
    HardwareClass string `json:"hardwareClass"`
    Model         string `json:"model"`
    DeviceFile    string `json:"deviceFile"`
    LinkDetected  string `json:"linkDetected"`
    ConfigStatus  string `json:"configStatus"`
}

type Ethernet struct {
    UniqueID           string `json:"uniqueId"`
    SysFSID            string `json:"sysFsId"`
    SysFSDeviceLink    string `json:"sysFsDeviceLink"`
    HardwareClass      string `json:"hardwareClass"`
    Model              string `json:"model"`
    Driver             string `json:"driver"`
    DriverModule       string `json:"driverModule"`
    DeviceFile         string `json:"deviceFile"`
    HWAddress          string `json:"hwAddress"`
    PermanentHWAddress string `json:"permanentHwAddress"`
    LinkDetected       string `json:"linkDetected"`
    ConfigStatus       string `json:"configStatus"`
    AttachedTo         string `json:"attachedTo"`
}

var (
    errPatternNotFound = fmt.Errorf("debug info string not found")
)

func GetHardwareInfo() *HardwareInfo {
    return parse()
}

func getRawHWData() ([]byte, error) {
    cmd := exec.Command("hwinfo")
    bytes, err := cmd.Output()
    if err != nil {
        return nil, err
    }

    pattern := regexp.MustCompile(endDebugPattern)
    indexes := pattern.FindSubmatchIndex(bytes)

    if len(indexes) == 0 {
        return nil, errPatternNotFound
    }

    return bytes[indexes[1]:], nil
}

func parse() *HardwareInfo {
    hwData, err := getRawHWData()
    if err != nil {
        log.Fatal(err)
    }

    hwInfo := &HardwareInfo{}

    pattern := regexp.MustCompile(titlePattern)
    indexes := pattern.FindAllStringSubmatchIndex(string(hwData), -1)
    for i := 0; i < len(indexes)-1; i++ {
        dataStart := indexes[i][1]
        dataEnd := indexes[i+1][0]
        title := parseTitle(strings.TrimSpace(string(hwData[indexes[i][0]:indexes[i][1]])))
        data := strings.TrimSpace(string(hwData[dataStart:dataEnd]))

        switch title {

        case "BIOS":
            reflectStruct(&hwInfo.BIOS, data)
            break

        case "System":
            reflectStruct(&hwInfo.System, data)
            break

        case "Main Memory":
            reflectStruct(&hwInfo.MainMemory, data)
            break

        case "FPU":
            fpu := FPU{}
            reflectStruct(&fpu, data)
            hwInfo.FPUS = append(hwInfo.FPUS, fpu)
            break

        case "DMA controller":
            dma := DMAController{}
            reflectStruct(&dma, data)
            hwInfo.DMAControllers = append(hwInfo.DMAControllers, dma)
            break

        case "PIC":
            pic := PIC{}
            reflectStruct(&pic, data)
            hwInfo.PICS = append(hwInfo.PICS, pic)
            break

        case "Keyboard controller":
            kc := KeyboardController{}
            reflectStruct(&kc, data)
            hwInfo.KeyboardControllers = append(hwInfo.KeyboardControllers, kc)
            break

        case "WLAN controller":
            wc := WLANController{}
            reflectStruct(&wc, data)
            hwInfo.WLANControllers = append(hwInfo.WLANControllers, wc)
            break

        case "SATA controller":
            sc := SATAController{}
            reflectStruct(&sc, data)
            hwInfo.SATAControllers = append(hwInfo.SATAControllers, sc)
            break

        case "PCI bridge":
            pciBridge := PCIBridge{}
            reflectStruct(&pciBridge, data)
            hwInfo.PCIBridges = append(hwInfo.PCIBridges, pciBridge)
            break

        case "ISA bridge":
            isaBridge := ISABridge{}
            reflectStruct(&isaBridge, data)
            hwInfo.ISABridges = append(hwInfo.ISABridges, isaBridge)
            break

        case "Communication controller":
            cc := CommunicationController{}
            reflectStruct(&cc, data)
            hwInfo.CommunicationControllers = append(hwInfo.CommunicationControllers, cc)
            break

        case "Audio device":
            audio := AudioDevice{}
            reflectStruct(&audio, data)
            hwInfo.AudioDevices = append(hwInfo.AudioDevices, audio)
            break

        case "Ethernet controller":
            ec := EthernetController{}
            reflectStruct(&ec, data)
            hwInfo.EthernetControllers = append(hwInfo.EthernetControllers, ec)
            break

        case "SMBus":
            smb := SMBus{}
            reflectStruct(&smb, data)
            hwInfo.SMBuses = append(hwInfo.SMBuses, smb)
            break

        case "Host bridge":
            hb := HostBridge{}
            reflectStruct(&hb, data)
            hwInfo.HostBridges = append(hwInfo.HostBridges, hb)
            break

        case "USB Controller":
            uc := USBController{}
            reflectStruct(&uc, data)
            hwInfo.USBControllers = append(hwInfo.USBControllers, uc)
            break

        case "Serial controller":
            sc := SerialController{}
            reflectStruct(&sc, data)
            hwInfo.SerialControllers = append(hwInfo.SerialControllers, sc)
            break

        case "System peripheral":
            sp := SystemPeripheral{}
            reflectStruct(&sp, data)
            hwInfo.SystemPeripherals = append(hwInfo.SystemPeripherals, sp)
            break

        case "VGA compatible controller":
            vcc := VGACompatibleController{}
            reflectStruct(&vcc, data)
            hwInfo.VGACompatibleControllers = append(hwInfo.VGACompatibleControllers, vcc)
            break

        case "LCD Monitor":
            monitor := LCDMonitor{}
            reflectStruct(&monitor, data)
            hwInfo.LCDMonitors = append(hwInfo.LCDMonitors, monitor)
            break

        case "Disk":
            disk := Disk{}
            reflectStruct(&disk, data)
            hwInfo.Disks = append(hwInfo.Disks, disk)
            break

        case "Partition":
            partition := Partition{}
            reflectStruct(&partition, data)
            hwInfo.Partitions = append(hwInfo.Partitions, partition)
            break

        case "Bluetooth Device":
            bluetooth := BluetoothDevice{}
            reflectStruct(&bluetooth, data)
            hwInfo.BluetoothDevices = append(hwInfo.BluetoothDevices, bluetooth)
            break

        case "Unclassified device":
            unknown := UnclassifiedDevice{}
            reflectStruct(&unknown, data)
            hwInfo.UnclassifiedDevices = append(hwInfo.UnclassifiedDevices, unknown)
            break

        case "Hub":
            hub := Hub{}
            reflectStruct(&hub, data)
            hwInfo.Hubs = append(hwInfo.Hubs, hub)
            break

        case "Keyboard":
            keyboard := Keyboard{}
            reflectStruct(&keyboard, data)
            hwInfo.Keyboards = append(hwInfo.Keyboards, keyboard)
            break

        case "USB Mouse":
            mouse := USBMouse{}
            reflectStruct(&mouse, data)
            hwInfo.USBMouses = append(hwInfo.USBMouses, mouse)
            break

        case "CPU":
            cpu := CPU{}
            reflectStruct(&cpu, data)
            hwInfo.CPUS = append(hwInfo.CPUS, cpu)
            break

        case "Loopback":
            loopback := Loopback{}
            reflectStruct(&loopback, data)
            hwInfo.Loopbacks = append(hwInfo.Loopbacks, loopback)
            break

        case "Ethernet":
            ethernet := Ethernet{}
            reflectStruct(&ethernet, data)
            hwInfo.Ethernets = append(hwInfo.Ethernets, ethernet)
            break
        }
    }

    return hwInfo
}

func reflectStruct(target interface{}, data string) {
    values := reflect.ValueOf(target).Elem()

    lines := strings.Split(data, "\n")
    for i := 1; i < len(lines); i++ {
        spacelessLine := strings.Replace(lines[i], " ", "", -1)
        splitData := strings.Split(strings.TrimSpace(spacelessLine), ":")
        fieldName := splitData[0]
        var fieldValue string
        if len(splitData) > 1 {
            fieldValue = splitData[1]
        } else {
            fieldValue = ""
        }
        structField := values.FieldByName(fieldName)
        if structField.Kind() == reflect.Invalid {
            continue
        } else {
            setValue(structField, fieldValue)
        }
    }
}

func setValue(field reflect.Value, value interface{}) {
    fieldType := field.Type()

    if fieldType.Kind() == reflect.Slice {
        newSlice := reflect.Append(field, reflect.ValueOf(value))
        field.Set(newSlice)
    } else {
        switch fieldType.Name() {
        case "string":
            field.SetString(value.(string))

        case "int64":
            parsedInt, err := strconv.ParseInt(value.(string), 10, 64)
            if err != nil {
                log.Fatalf(
                    "failed to parse value. type: %s, value: %s, err: %s",
                    fieldType.Name(),
                    value,
                    err,
                )
            }
            field.SetInt(parsedInt)
        }
    }

}

func parseTitle(title string) string {
    strsplit := strings.Split(title, ":")
    var parenthesisSplit []string
    var firstSplit string
    if len(strsplit) == 3 {
        firstSplit = strsplit[2]
        parenthesisSplit = strings.Split(firstSplit, "(")

    } else {
    }
    if len(parenthesisSplit) > 1 {
        return strings.Join(strings.Fields(parenthesisSplit[0])[1:], " ")
    } else if len(parenthesisSplit) == 1 {
        return strings.Join(strings.Fields(firstSplit)[1:], " ")
    } else {
        return " "
    }
}

func main() {
    info := parse()
    fmt.Println(info.LCDMonitors[0].Model, info.LCDMonitors[0].Vendor, info.LCDMonitors[0].Device, info.LCDMonitors[0].UniqueID)
    fmt.Println(info.System.UniqueID, info.System.Model, info.System.HardwareClass, info.System.Formfactor, info.System.ConfigStatus)
    fmt.Println(info.SystemPeripherals[0].UniqueID)
}
anandharaj-dotworld commented 2 years ago

Now it's running both sudo and non sudo

himidori commented 2 years ago

Hi. I didn't quite get what exactly have you changed? Can you make a PR please?

anandharaj-dotworld commented 2 years ago
func parseTitle(title string) string {
    strsplit := strings.Split(title, ":")
    var parenthesisSplit []string
    var firstSplit string
    if len(strsplit) == 3 {
        firstSplit = strsplit[2]
        parenthesisSplit = strings.Split(firstSplit, "(")

    } else {
    }
    if len(parenthesisSplit) > 1 {
        return strings.Join(strings.Fields(parenthesisSplit[0])[1:], " ")
    } else if len(parenthesisSplit) == 1 {
        return strings.Join(strings.Fields(firstSplit)[1:], " ")
    } else {
        return " "
    }
}

and

func reflectStruct(target interface{}, data string) {
    values := reflect.ValueOf(target).Elem()

    lines := strings.Split(data, "\n")
    for i := 1; i < len(lines); i++ {
        spacelessLine := strings.Replace(lines[i], " ", "", -1)
        splitData := strings.Split(strings.TrimSpace(spacelessLine), ":")
        fieldName := splitData[0]
        var fieldValue string
        if len(splitData) > 1 {
            fieldValue = splitData[1]
        } else {
            fieldValue = ""
        }
        structField := values.FieldByName(fieldName)
        if structField.Kind() == reflect.Invalid {
            continue
        } else {
            setValue(structField, fieldValue)
        }
    }
}

This above code i changes

himidori commented 2 years ago

Ok. Send a PR and I will merge it