Example #1
0
func loadIni() {
	usr, _ := user.Current()
	configPath := filepath.Join(usr.HomeDir, ".goboom")
	iniFile := filepath.Join(configPath, "config.ini")
	dbFilePath = filepath.Join(configPath, "rankdb.csv")

	if _, err := os.Stat(configPath); err != nil {
		err := os.Mkdir(configPath, os.ModePerm)
		if err != nil {
			fmt.Println("failed to create config dir")
		}
	}

	config = Config{
		DmenuParams: "-b -i -nb black -nf orange -sb black -p \">\"",
		Ignore:      []string{"X", "su"},
	}
	if _, err := os.Stat(iniFile); err != nil {
		newCfg := ini.Empty()
		newCfg.NameMapper = ini.TitleUnderscore

		err := ini.ReflectFrom(newCfg, &config)
		if err != nil {
			panic(err)
		}

		newCfg.SaveTo(iniFile)
	} else {
		if err := ini.MapToWithMapper(&config, ini.TitleUnderscore, iniFile); err != nil {
			panic(err)
		}
	}
}
func newIniConfig(dest *Destination) (*ini.File, error) {
	iniCfg := ini.Empty()
	path := configPath(dest)
	logrus.Debugf("using config file: %s", path)
	if _, err := os.Stat(path); err != nil {
		// TODO: handle os.isnotexist(path) and other errors differently
		// error reading config file, create empty config ini.
		logrus.Debugf("no config files found, initializing empty ini")
	} else {
		err = iniCfg.Append(path)
		if err != nil {
			return nil, err
		}
	}

	return iniCfg, nil
}
Example #3
0
// Config generates an minimalistic config ini file
// in *ini.File format. You may then use SaveTo(path)
// to save it
func (proc *Process) Config() (f *ini.File) {
	f = ini.Empty()
	f.NewSection("global")
	f.Section("global").NewKey("pid", proc.PidFile)
	f.Section("global").NewKey("error_log", proc.ErrorLog)
	f.NewSection("www")
	f.Section("www").NewKey("listen", proc.Listen)
	f.Section("www").NewKey("pm", "dynamic")
	f.Section("www").NewKey("pm.max_children", "5")
	f.Section("www").NewKey("pm.start_servers", "2")
	f.Section("www").NewKey("pm.min_spare_servers", "1")
	f.Section("www").NewKey("pm.max_spare_servers", "3")
	if proc.User != "" {
		f.Section("www").NewKey("user", proc.User)
	}
	return
}
Example #4
0
func newIniConfig(dest *Destination) (*ini.File, error) {
	iniCfg := ini.Empty()
	// TODO: Move to const.
	filename := filepath.Join(dest.Path, "config")
	logrus.Debugf("using config file: %s", filename)
	if _, err := os.Stat(filename); err != nil {
		// TODO: handle os.isnotexist(filename) and other errors differently
		// error reading config file, create empty config ini.
		logrus.Debugf("no config files found, initializing empty ini")
	} else {
		err = iniCfg.Append(filename)
		if err != nil {
			return nil, err
		}
	}

	return iniCfg, nil
}
Example #5
0
// public for external handler
func (cman *ConfigMan) CreateClientConfig(file string, user string, addonAddr string) (err error) {
	var f *os.File
	if file == NULL {
		f = os.Stdout
	} else {
		f, err = os.OpenFile(file, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0644)
		if err != nil {
			return err
		}
		defer f.Close()
	}
	defer f.Sync()

	conf := new(clientConf)
	setFieldsDefaultValue(conf)
	ii := ini.Empty()
	// client section
	dc, _ := ii.NewSection(CF_CLIENT)
	dc.Comment = _CLT_CONF_HEADER[1:]
	dc.ReflectFrom(conf)
	// prepare server addr
	if addonAddr == NULL {
		cman.sConf.Listen = "localhost:9008"
	} else {
		err = IsValidHost(addonAddr)
		cman.sConf.Listen = addonAddr
		if err != nil {
			return
		}
	}
	err = cman.sConf.generateConnInfoOfUser(ii, user)
	if err == nil {
		_, err = ii.WriteTo(f)
		if addonAddr == NULL {
			fmt.Fprint(f, _NOTICE_MOD_ADDR)
		}
	}
	return
}
Example #6
0
// public for external handler
func CreateServerConfigTemplate(file string, keyOpt string) (err error) {
	var f *os.File
	if file == NULL {
		f = os.Stdout
	} else {
		f, err = os.OpenFile(file, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0600)
		if err != nil {
			return
		}
		defer f.Close()
	}
	defer f.Sync()

	d5sConf := new(serverConf)
	d5sConf.setDefaultValue()
	// uppercase algo name
	keyOpt = strings.ToUpper(keyOpt)
	d5sConf.privateKey, err = GenerateDSAKey(keyOpt)
	if err != nil {
		return
	}

	ii := ini.Empty()
	ds, _ := ii.NewSection(CF_SERVER)
	ds.Comment = _SER_CONF_HEADER[1:]
	err = ds.ReflectFrom(d5sConf)
	if err != nil {
		return
	}
	ks, _ := ii.NewSection(CF_PRIVKEY)
	keyBytes := MarshalPrivateKey(d5sConf.privateKey)

	ks.Comment = _SER_CONF_MIDDLE[1:]
	ks.NewKey(CF_KEY, base64.StdEncoding.EncodeToString(keyBytes))
	_, err = ii.WriteTo(f)
	return
}
Example #7
0
func init() {
	cfg = ini.Empty()
}
Example #8
0
// reload считывает данные с ini-файла и загружает в структуру. При необходимости инициализирует данные значениями по умолчанию
func reloadSettings() error {
	var key *ini.Key
	var err error
	var value int

	defUpdSetDelayInt, _ := strconv.Atoi(defUpdSetDelay)
	defUpdDataDelayInt, _ := strconv.Atoi(defUpdDataDelay)

	// открыть ini-файл
	cf, err = ini.Load(nameIniFile)
	if err != nil {
		if os.IsNotExist(err) { // файл с настройками не найден?
			cf = ini.Empty() // создать новый объект с настройками
		} else {
			return err
		}
	}

	// обработать секцию "general" с основными настройками
	section, err := cf.GetSection("general")
	if err != nil {
		section, err = cf.NewSection("general") // секции нет в ini-файле? Тогда создать.
		if err != nil {
			return err // если не удалось создать, то продолжать бессмысленно
		}
		section.Comment = "Основные настройки"
	}

	// перечитывать настройки каждые .... сек
	key, err = section.GetKey("updsetdelay")
	if err != nil {
		key, err = section.NewKey("updsetdelay", defUpdSetDelay)
		if err != nil {
			return err
		}
		key.Comment = "Перечитывать настройки каждые ... сек."
	}
	value = key.RangeInt(defUpdSetDelayInt, 5, 1000000) // значение в пределах 5 - 1000000 секунд. При ошибке инициализация значением по умолчанию
	key.SetValue(strconv.Itoa(value))
	cfstruct.updsetdelay = value

	// обновлять данные плейлиста каждые .... сек
	key, err = section.GetKey("upddatadelay")
	if err != nil {
		key, err = section.NewKey("upddatadelay", defUpdDataDelay)
		if err != nil {
			return err
		}
		key.Comment = "Обновлять данные плейлиста каждые ... сек."
	}
	value = key.RangeInt(defUpdDataDelayInt, 300, 1000000) // значение в пределах 300 - 1000000 секунд. При ошибке инициализация значением по умолчанию
	key.SetValue(strconv.Itoa(value))
	cfstruct.upddatadelay = value

	// Имя файла плейлиста и путь до него.
	key, err = section.GetKey("pathplaylist")
	if err != nil {
		key, err = section.NewKey("pathplaylist", defPathPlaylist)
		if err != nil {
			return err
		}
		key.Comment = "Имя файла плейлиста и путь до него."
	}
	cfstruct.pathplaylist = key.String()

	// Количество параллельных потоков для парсинга сайта
	key, err = section.GetKey("workers")
	if err != nil {
		key, err = section.NewKey("workers", strconv.Itoa(defWorkers))
		if err != nil {
			return err
		}
		key.Comment = "Количество параллельных потоков для парсинга сайта. По умолчанию равен кол-ву ядер процессора."

	}
	value = key.RangeInt(defWorkers, 1, 100) // значение в пределах 1 - 100 отдельных потоков. При ошибке инициализация значением по умолчанию
	key.SetValue(strconv.Itoa(value))
	cfstruct.workers = value

	// секция "каналы"
	section, err = cf.GetSection("channels")
	if err != nil {
		section, err = cf.NewSection("channels") // секции нет в ini-файле? Создать секцию.
		if err != nil {
			return err
		}
	}
	section.Comment = "Список каналов. Пример строки: -:rossija"

	// секция содержит список каналов
	ch := section.Keys() // получить массив списка каналов
	cfstruct.channels = ch

	err = cf.SaveTo(nameIniFile) // сохранить файл с значениями по умолчанию
	if err != nil {
		return err
	}

	return nil
}