Source

hgfilemerge / __init__.py

# -*- coding: utf-8 -*-

import os
import logging

log = logging.getLogger(__name__)

class HgFileMerge():
    
    def __init__(self):
        self.base_path = '.'
        self.merge_groups = {}
    
    def configure_from_dict(self, d):
        if 'base_path' in d:
            self.base_path = d['base_path']
        if 'merge_groups' in d:
            for group in d['merge_groups']:
                valid_group = {}
                valid_group['name'] = group['name']
                valid_group['files'] = []
                for file_ in group['files']:
                    file_path = os.path.join(self.base_path, file_)
                    if not os.path.exists(file_path):
                        log.warning(u'File %s does not exist' % file_path)
                    elif not os.path.isfile(file_path):
                        log.warning(u'File %s is not a file (directory maybe?)' % file_path)
                    else:
                        valid_group['files'].append(file_)
                self.merge_groups[valid_group['name']] = valid_group['files']
    
    def configure_from_file(self, path):
        import codecs
        
        def yml_configurer(f):
            from yaml import load
            return load(f)
        
        configurers = {
            'yml': yml_configurer,
            }
        
        configurer = (configurers.get(path[path.rfind('.'):]) or
                      configurers.get('yml'))
        
        with codecs.open(path, 'r', 'utf-8') as f:
            self.configure_from_dict(configurer(f))
    
    def get_merge_groups(self):
        """Returns merge groups names"""
        return self.merge_groups.keys()
    
    def get_merged_lines(self, group_name):
        import codecs
        
        ret_val = []
        for filename in self.merge_groups[group_name]:
            with codecs.open(os.path.join(self.base_path, filename), 'r', 'utf-8') as f:
                ret_val += f.readlines()
        return ret_val

    def save(self, group_name):
        import codecs

        lines_to_save = self.get_merged_lines(group_name)
        with codecs.open(os.path.join(self.base_path, group_name), 'w', 'utf-8') as f:
            f.writelines(lines_to_save)