Skip to content

Commit

Permalink
Merge pull request #19 from jedwards4b/feature/me2flexi
Browse files Browse the repository at this point in the history
add translater from manage_externals
  • Loading branch information
jedwards4b authored Feb 29, 2024
2 parents 678bae8 + 91df5a0 commit 14868db
Show file tree
Hide file tree
Showing 6 changed files with 286 additions and 28 deletions.
5 changes: 2 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ Git-fleximod is a Python-based tool that extends Git's submodule and sparse chec
Basic Usage:
git fleximod <command> [options]
Available Commands:
checkout: Checkout submodules according to git submodule hash configuration.
status: Display the status of submodules.
update: Update submodules to the tag indicated in .gitmodules variable fxtag.
test: Make sure that fxtags and submodule hashes are consistant,
Expand Down Expand Up @@ -55,9 +54,9 @@ Git-fleximod is a Python-based tool that extends Git's submodule and sparse chec

Here are some common usage examples:

Checkout submodules, including optional ones:
Update all submodules, including optional ones:
```bash
git fleximod checkout --optional
git fleximod update --optional
```

Updating a specific submodule to the fxtag indicated in .gitmodules:
Expand Down
5 changes: 3 additions & 2 deletions git_fleximod/git_fleximod.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,8 +132,9 @@ def submodule_sparse_checkout(
shutil.copy(sparsefile, gitsparse)

# Finally checkout the repo
sprepo_git.git_operation("fetch", "--depth=1", "origin", "--tags")
sprepo_git.git_operation("fetch", "origin", "--tags")
sprepo_git.git_operation("checkout", tag)

print(f"Successfully checked out {name:>20} at {tag}")
rgit.config_set_value(f'submodule "{name}"',"active","true")
rgit.config_set_value(f'submodule "{name}"',"url",url)
Expand Down Expand Up @@ -242,7 +243,7 @@ def submodules_status(gitmodules, root_dir):
ahash = git.git_operation("status").partition("\n")[0].split()[-1]
if tag and atag == tag:
print(f" {name:>20} at tag {tag}")
elif tag and ahash == tag:
elif tag and ahash[:len(tag)] == tag:
print(f" {name:>20} at hash {ahash}")
elif tag:
print(f"s {name:>20} {atag} {ahash} is out of sync with .gitmodules {tag}")
Expand Down
22 changes: 14 additions & 8 deletions git_fleximod/gitinterface.py
Original file line number Diff line number Diff line change
@@ -1,25 +1,31 @@
import os
import sys
from . import utils
from pathlib import Path

class GitInterface:
def __init__(self, repo_path, logger):
logger.debug("Initialize GitInterface for {}".format(repo_path))
self.repo_path = repo_path
if isinstance(repo_path, str):
self.repo_path = Path(repo_path).resolve()
elif isinstance(repo_path, Path):
self.repo_path = repo_path.resolve()
else:
raise TypeError("repo_path must be a str or Path object")
self.logger = logger
try:
import git

self._use_module = True
try:
self.repo = git.Repo(repo_path) # Initialize GitPython repo
self.repo = git.Repo(str(self.repo_path)) # Initialize GitPython repo
except git.exc.InvalidGitRepositoryError:
self.git = git
self._init_git_repo()
msg = "Using GitPython interface to git"
except ImportError:
self._use_module = False
if not os.path.exists(os.path.join(repo_path, ".git")):
if not (repo_path / ".git").exists():
self._init_git_repo()
msg = "Using shell interface to git"
self.logger.info(msg)
Expand All @@ -32,13 +38,13 @@ def _git_command(self, operation, *args):
except Exception as e:
sys.exit(e)
else:
return ["git", "-C", self.repo_path, operation] + list(args)
return ["git", "-C", str(self.repo_path), operation] + list(args)

def _init_git_repo(self):
if self._use_module:
self.repo = self.git.Repo.init(self.repo_path)
self.repo = self.git.Repo.init(str(self.repo_path))
else:
command = ("git", "-C", self.repo_path, "init")
command = ("git", "-C", str(self.repo_path), "init")
utils.execute_subprocess(command)

# pylint: disable=unused-argument
Expand All @@ -58,7 +64,7 @@ def config_get_value(self, section, name):
config = self.repo.config_reader()
return config.get_value(section, name)
else:
cmd = ("git", "-C", self.repo_path, "config", "--get", f"{section}.{name}")
cmd = ("git", "-C", str(self.repo_path), "config", "--get", f"{section}.{name}")
output = utils.execute_subprocess(cmd, output_to_caller=True)
return output.strip()

Expand All @@ -68,6 +74,6 @@ def config_set_value(self, section, name, value):
writer.set_value(section, name, value)
writer.release() # Ensure changes are saved
else:
cmd = ("git", "-C", self.repo_path, "config", f"{section}.{name}", value)
cmd = ("git", "-C", str(self.repo_path), "config", f"{section}.{name}", value)
self.logger.info(cmd)
utils.execute_subprocess(cmd, output_to_caller=True)
39 changes: 24 additions & 15 deletions git_fleximod/gitmodules.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import os
import shutil
from configparser import ConfigParser
from pathlib import Path
from configparser import RawConfigParser, ConfigParser
from .lstripreader import LstripReader


class GitModules(ConfigParser):
class GitModules(RawConfigParser):
def __init__(
self,
logger,
confpath=os.getcwd(),
confpath=Path.cwd(),
conffile=".gitmodules",
includelist=None,
excludelist=None,
Expand All @@ -25,25 +25,32 @@ def __init__(
confpath, conffile, includelist, excludelist
)
)
ConfigParser.__init__(self)
self.conf_file = os.path.join(confpath, conffile)
# first create a backup of this file to be restored on deletion of the object
shutil.copy(self.conf_file, self.conf_file + ".save")
self.read_file(LstripReader(self.conf_file), source=conffile)
super().__init__()
self.conf_file = (Path(confpath) / Path(conffile))
if self.conf_file.exists():
self.read_file(LstripReader(str(self.conf_file)), source=conffile)
self.includelist = includelist
self.excludelist = excludelist
self.isdirty = False

def reload(self):
self.clear()
if self.conf_file.exists():
self.read_file(LstripReader(str(self.conf_file)), source=self.conf_file)


def set(self, name, option, value):
"""
Sets a configuration value for a specific submodule:
Ensures the appropriate section exists for the submodule.
Calls the parent class's set method to store the value.
"""
self.isdirty = True
self.logger.debug("set called {} {} {}".format(name, option, value))
section = f'submodule "{name}"'
if not self.has_section(section):
self.add_section(section)
ConfigParser.set(self, section, option, str(value))
super().set(section, option, str(value))

# pylint: disable=redefined-builtin, arguments-differ
def get(self, name, option, raw=False, vars=None, fallback=None):
Expand All @@ -62,12 +69,14 @@ def get(self, name, option, raw=False, vars=None, fallback=None):
return None

def save(self):
print("Called gitmodules save, not expected")
# self.write(open(self.conf_file, "w"))

if self.isdirty:
self.logger.info("Writing {}".format(self.conf_file))
with open(self.conf_file, "w") as fd:
self.write(fd)
self.isdirty = False

def __del__(self):
self.logger.debug("Destroying GitModules object")
shutil.move(self.conf_file + ".save", self.conf_file)
self.save()

def sections(self):
"""Strip the submodule part out of section and just use the name"""
Expand Down
Loading

0 comments on commit 14868db

Please sign in to comment.