import os

from acbs import bashvar

class AB3Cfg(object):

    def __init__(self, path) -> None:
        '''
        Class representing autobuild3 config file.

        :param path: path to the ab3cfg.sh file, with the filename
        '''
        self.cfgpath = path
        self.file = None
        self.vars = None
        self.stage2 = False
        try:
            self.file = open(self.cfgpath, 'rt')
        except IOError:
            # You run ACBS then you should have AB3, eh?
            raise RuntimeError(f'Autobuild3 config file {self.cfgpath} does not exist\n' +
                               'Unable to read Autobuild3 config file.')
        if self.file:
            self.parse()

    def parse(self):
        '''
        Parse the ab3cfg.sh file.
        '''
        if self.file:
            try:
                self.vars = bashvar.eval_bashvar(self.file.read(), filename=self.cfgpath)
            except Exception as e:
                raise RuntimeError(f'Error parsing autobuild3 config file: {e}.')

    def is_in_stage2(self) -> bool:
        '''
        Return True if ab3 is in stage 2 mode.
        '''
        if self.vars:
            self.stage2 = ((self.vars.get('ABSTAGE2') == '1') or False)
        return self.stage2

@@ -266,33 +266,8 @@
 ath%0A
-        self.file = None%0A
     
@@ -344,19 +344,12 @@
     
-self.file =
+with
  ope
@@ -369,16 +369,64 @@
 h, 'rt')
+ as cfgfile:%0A                self.parse(cfgfile)
 %0A       
@@ -437,15 +437,22 @@
 ept 
-IOError
+Exception as e
 :%0A  
@@ -673,55 +673,15 @@
 e.')
-%0A        if self.file:%0A            self.parse()
+ from e
 %0A%0A  
@@ -696,16 +696,22 @@
 rse(self
+, file
 ):%0A     
@@ -767,34 +767,8 @@
 '''%0A
-        if self.file:%0A    
     
@@ -768,36 +768,32 @@
 ''%0A        try:%0A
-    
             self
@@ -821,21 +821,16 @@
 bashvar(
-self.
 file.rea
@@ -861,28 +861,24 @@
 th)%0A        
-   
- 
 except Excep
@@ -880,36 +880,32 @@
 Exception as e:%0A
-    
             rais
@@ -965,16 +965,23 @@
 : %7Be%7D.')
+ from e
 %0A%0A    de

improve file reading and parsing logic