fix: allocate the correct size for byte array to read info from existing files

This commit is contained in:
oscar 2022-09-22 09:24:10 +12:00
parent 9c56ec0d85
commit f25a6f7806
2 changed files with 34 additions and 7 deletions

View File

@ -47,16 +47,31 @@ func GetConfig() (*Config, error) {
file, err := getConfigFile(ConfigFileName)
if err != nil {
if err == ErrConfigNotInitialized {
config, err := initializeConfig(file)
if err != nil {
return config, err
}
return initializeConfig(file)
}
return nil, err
}
defer file.Close()
return getConfig(file)
}
func (config *Config) Summarize() {
fmt.Printf("The project path is %s\nThe volume path is %s\n", config.ProjectPath, config.VolumePath)
if config.LoginCredential.Username != "" && config.LoginCredential.Password != "" {
fmt.Printf("Login credential [%s] is configured\n", config.LoginCredential.Username)
}
if len(config.RepositoryConfig) > 0 {
for name := range config.RepositoryConfig {
fmt.Printf("Repository [%s] is added\n", name)
}
} else {
fmt.Println("No repository is added")
}
}
func initializeConfig(w io.WriteCloser) (*Config, error) {
config := &Config{}
fmt.Printf("Set the project path: ")
@ -109,13 +124,23 @@ func initializeConfig(w io.WriteCloser) (*Config, error) {
return config, nil
}
func getConfig(f io.Reader) (*Config, error) {
func getConfig(f *os.File) (*Config, error) {
config := &Config{}
bytes := make([]byte, 0)
_, err := f.Read(bytes)
info, err := f.Stat()
if err != nil {
return nil, err
}
bytes := make([]byte, info.Size())
n, err := f.Read(bytes)
if err != nil {
return nil, err
}
if n == 0 {
// The file exists, but it's empty file, so we need to initalize
return initializeConfig(f)
}
err = json.Unmarshal(bytes, &config)
if err != nil {

View File

@ -14,6 +14,8 @@ func main() {
log.Fatalln(err)
}
config.Summarize()
// Init tasks
taskItems := []tasks.Tasker{