/// <inheritdoc />
        public static IObservable<IObservableRepository> Clone(
            string sourceUrl,
            string workingDirectory,
            IObserver<Tuple<string, int>> observer,
            CredentialsHandler credentials = null)
        {
            var isCancelled = false;
            var options = new CloneOptions
            {
                Checkout = true,
                CredentialsProvider = credentials,
                OnTransferProgress = progress =>
                {
                    // TODO: how should we signal for the "indexing objects" events
                    var p = (100 * progress.ReceivedObjects) / progress.TotalObjects;
                    var receivingMessage = String.Format("Receiving objects:  {0}% ({1}/{2})", p, progress.ReceivedObjects, progress.TotalObjects);
                    observer.OnNext(Tuple.Create(receivingMessage, p));
                    return !isCancelled;
                },
                IsBare = false,
                OnCheckoutProgress = ProgressFactory.CreateHandlerWithoutMessages(observer)
            };

            var directoryInfo = new DirectoryInfo(workingDirectory);
            var initialMessage = String.Format("Cloning into '{0}'...", directoryInfo.Name);
            observer.OnNext(Tuple.Create(initialMessage, 0));

            return Observable.Create<ObservableRepository>(subj =>
            {
                var sub = Observable.Start(() =>
                {
                    var directory = Repository.Clone(sourceUrl, workingDirectory, options);

                    observer.OnNext(Tuple.Create("clone completed", 100));
                    observer.OnCompleted();

                    return new ObservableRepository(directory, credentials);
                }, Scheduler.Default).Subscribe(subj);

                return new CompositeDisposable(
                    sub,
                    Disposable.Create(() =>
                    {
                        isCancelled = true;
                        observer.OnCompleted();
                    }));
            });
        }
示例#2
0
        public Task<List<ISourceItem>> FetchAllFiles(BuildConfig config)
        {

            string gitFolder = config.BuildFolder + "\\git";

            //// temporary hack...
            //// git-pull does not work
            //if (Directory.Exists(gitFolder)) {
            //    Directory.Delete(gitFolder, true);
            //}

            if (!Directory.Exists(gitFolder))
            {
                Directory.CreateDirectory(gitFolder);


                Console.WriteLine("Cloning repository " + config.SourceUrl);

                CloneOptions clone = new CloneOptions();
                clone.CredentialsProvider = CredentialsHandler;
                var rep = Repository.Clone(config.SourceUrl, gitFolder, clone);

                Console.WriteLine("Repository clone successful");
            }
            else {
                Console.WriteLine("Fetching remote Repository");
                var rep = new Repository(gitFolder);
                FetchOptions options = new FetchOptions();
                options.CredentialsProvider = CredentialsHandler;
                Remote remote = rep.Network.Remotes["origin"];

                //Commands.Fetch(rep,remote.Name,)

                //rep.Fetch(remote.Name, options);
                var master = rep.Branches["master"];
                Commands.Pull(rep, new Signature("IISCI", "*****@*****.**", DateTime.Now),  new PullOptions()
                {
                    FetchOptions = options,
                    MergeOptions = new MergeOptions() { 
                        MergeFileFavor = MergeFileFavor.Theirs,
                        CommitOnSuccess = true                        
                    }
                });
                Console.WriteLine("Fetch successful");
            }

            List<ISourceItem> files = new List<ISourceItem>();

            EnumerateFiles( new DirectoryInfo(gitFolder), files, "" );


            Parallel.ForEach(files, file =>
            {
                var md5 = System.Security.Cryptography.MD5.Create();
                ((GitSourceItem)file).Version = Convert.ToBase64String(md5.ComputeHash(File.ReadAllBytes(file.Url)));
            });


            return Task.FromResult(files);
        }
示例#3
0
        public void CloneRepo()
        {
            var scd = BuildSelfCleaningDirectory();
            CloneOptions options = new CloneOptions();
            var credentials = new UsernamePasswordCredentials();
            credentials.Username = Constants.Identity.Name;
            credentials.Password = "******";
            options.CredentialsProvider += (url, fromUrl, types) => credentials;

            string clonedRepoPath = Repository.Clone(testUrl, scd.DirectoryPath, options);
            string file = Path.Combine(scd.DirectoryPath, "testpush.txt");
            var rbg = new RandomBufferGenerator(30000);
            using (var repo = new Repository(clonedRepoPath)) {
                for (int i = 0; i < 1; i++) {
                    var network = repo.Network.Remotes.First();
                    FetchOptions fetchOptions = new FetchOptions();
                    fetchOptions.CredentialsProvider += (url, fromUrl, types) => credentials;
                    repo.Fetch(network.Name, fetchOptions);

                    File.WriteAllBytes(file, rbg.GenerateBufferFromSeed(30000));
                    repo.Stage(file);
                    Signature author = Constants.Signature;

                    Commit commit = repo.Commit($"Here's a commit {i + 1} i made!", author, author);
                    PushOptions pushOptions = new PushOptions();
                    pushOptions.CredentialsProvider += (url, fromUrl, types) => credentials;
                    repo.Network.Push(repo.Branches["master"], pushOptions);
                }
            }
        }
        public GitRepositoryContext GetRepositoryContext()
        {
            args.Validate();

            var gitRootDirectory = Path.Combine(args.DestinationPath);
            var gitDirectory = Path.Combine(gitRootDirectory, ".git");
            if (Directory.Exists(gitDirectory))
            {
                Log.WriteLine("Deleting existing .git folder from '{0}' to force new checkout from url", gitDirectory);
                DeleteGitDirectory(gitDirectory);
            }

            var credentials = args.Credentials;

            Log.WriteLine("Retrieving git info from url '{0}'", args.Url);

            var cloneOptions = new CloneOptions();
            cloneOptions.IsBare = true;
            cloneOptions.Checkout = false;
            cloneOptions.CredentialsProvider = (url, usernameFromUrl, types) => credentials;

            var repoPath = Repository.Clone(args.Url, gitDirectory, cloneOptions);
            var repository = new Repository(repoPath);
            var repoContext = new GitRepositoryContext(repository, credentials, true, args.Url);
            return repoContext;
        }
        public GitRepositoryContext GetRepositoryContext()
        {
            args.Validate();

            var gitRootDirectory = Path.Combine(args.DestinationPath);
            var gitDirectory = Path.Combine(gitRootDirectory, ".git");

            var credentials = args.Credentials;

            if (fileSystem.DirectoryExists(gitDirectory))
            {
                Log.WriteLine("Git repository already exists, using existing instance from url '{0}'", args.Url);

                var repository = new Repository(gitDirectory);
                var repoContext = new GitRepositoryContext(repository, credentials, true, args.Url, fileSystem);
                return repoContext;
            }
            else
            {
                Log.WriteLine("Cloning git repository from url '{0}'", args.Url);

                var cloneOptions = new CloneOptions
                {
                    IsBare = true,
                    Checkout = false,
                    CredentialsProvider = (url, usernameFromUrl, types) => credentials
                };

                var repoPath = Repository.Clone(args.Url, gitDirectory, cloneOptions);
                var repository = new Repository(repoPath);
                var repoContext = new GitRepositoryContext(repository, credentials, true, args.Url, fileSystem);
                return repoContext;
            }
        }
        public void Clone()
        {
            var co = new CloneOptions();
            co.RecurseSubmodules = true;
            co.OnProgress = ProgressChanged;

            Repository.Clone("git://github.com/SirCmpwn/TrueCraft.git", TrueCraftDir, co);
        }
示例#7
0
        public static void Main(string[] args)
        {
            try
            {
                log("started...");
                var repoUrl = args[0];
                var branchName = "master";
                var username = args[1];
                var password = "";
                if (args.Length == 3)
                {
                    password = args[2];
                }
                var pathSplit = repoUrl.Split('/');
                var repoName = pathSplit.Last();
                var author = new Signature("scarletapi", "@gmail", DateTime.Now);

                var repoDir = new DirectoryInfo(Path.Combine(Directory.GetCurrentDirectory(), repoName));
                var repoPath = repoDir.FullName;

                if (String.IsNullOrEmpty(username))
                {
                    throw new Exception("Must have username");
                }

                if (String.IsNullOrEmpty(password))
                {
                    repoUrl = repoUrl.Replace(pathSplit[2], String.Format("{0}@{2}", username, password, pathSplit[2]));
                }
                else
                {
                    repoUrl = repoUrl.Replace(pathSplit[2], String.Format("{0}:{1}@{2}", username, password, pathSplit[2]));
                }

                log("checking if repo exists");
                if (!repoDir.Exists || !Repository.IsValid(repoPath))
                {
                    if (repoDir.Exists)
                    {
                        repoDir.Delete(true);
                    }

                    var cloneOptions = new CloneOptions();
                    cloneOptions.BranchName = branchName;

                    log("cloning {0} repository at url {1}", repoName, repoUrl);
                    repoUrl = Repository.Clone(repoUrl, repoPath, cloneOptions);
                    using (var repo = new LibGit2Sharp.Repository(repoPath))
                    {
                        repo.Checkout(repo.Branches[branchName], new CheckoutOptions());
                    }
                }
            }
            catch (Exception e)
            {
                log("ERROR: {0}", e.Message);
            }
        }
示例#8
0
        private static void Main(string[] args)
        {
            var result = CommandLine.Parser.Default.ParseArguments<Options>(args);
              if (!result.Errors.Any())
              {
            string url = result.Value.Repository;

            var brancOption = result.Value.Branch;
            var branchSepIndex = brancOption.IndexOf('/');
            if (branchSepIndex > 0)
            {
              var credentials = new UsernamePasswordCredentials
            {
              Username = result.Value.UserName,
              Password = result.Value.Password
            };
              CredentialsHandler credHandler = (s, fromUrl, types) => credentials;

              var remote = brancOption.Substring(0, branchSepIndex);
              var branch = brancOption.Substring(branchSepIndex+1, brancOption.Length - branchSepIndex-1);

              var workingDirectory = result.Value.LocalRepoPath;

              var isLocalRepoExist = Repository.Discover(workingDirectory);
              if (isLocalRepoExist == null)
              {
            var cloneOptions = new CloneOptions {CredentialsProvider = credHandler};
            Repository.Clone(url, workingDirectory, cloneOptions);
              }

              Repository repo = null;
              try
              {
            var tagName = result.Value.TagName;
            repo = new Repository(workingDirectory);
            //repo.Fetch(remote, new FetchOptions(){CredentialsProvider = credHandler});
            repo.Network.Pull(new Signature(result.Value.UserName,result.Value.Email, new DateTimeOffset()),
              new PullOptions() { FetchOptions = new FetchOptions() { CredentialsProvider = credHandler } });
            repo.ApplyTag(tagName);
            PushChanges(repo, credHandler, remote, branch, tagName);
            Console.WriteLine("Tagged :{0}", result.Value.TagName);
              }
              catch (Exception ex)
              {
            Console.WriteLine("Error happened {0}", ex.Message);
              }
              finally
              {
            if (repo != null) repo.Dispose();
              }
            }
              }
              Console.ReadLine();
        }
示例#9
0
 public static void Clone(string sourceUrl, string workingDir)
 {
     var cloneOptions = new CloneOptions();
     cloneOptions.IsBare = false;
     cloneOptions.Checkout = true;
     cloneOptions.CredentialsProvider = new LibGit2Sharp.Handlers.CredentialsHandler((a, b, c) => new UsernamePasswordCredentials()
     {
         Username = ApplicationConfiguration.Get("pandora_git_username"),
         Password = ApplicationConfiguration.Get("pandora_git_password")
     });
     Repository.Clone(sourceUrl, workingDir, cloneOptions);
 }
示例#10
0
        public override async Task<JobResult> Run()
        {
            var args = JobDescriptor.GetArgumentsJson<CloneJobArgs>();
            var fullname = args.Url.Replace("https://github.com/", "")
                                    .Replace("http://github.com/", "")
                                    .Replace(".git", "");
            var clonePathAbs = _codeLocationRepository.GetCodeLocationLocalPath(fullname);
            return await Task.Run(() =>
            {
                var options = new CloneOptions()
                {
                    BranchName = args.Branch,
                    IsBare = args.Bare,
                    Checkout = true,
                    CredentialsProvider = (_url, _user, _cred) => new UsernamePasswordCredentials
                    {
                        Username = args.Username,
                        Password = _apiRepository.GetUserToken(args.Username)
                    }
                };
                try
                {
                    var result = _repositoryController.Clone(args.Url, clonePathAbs, options);
                    
                    // create an entry for the repository in our db, so we can link commits to it
                    var codelocation = _codeLocationRepository.CreateCodeLocation(fullname, args.RepoName, args.Username);

                    // let other workers know that this worker has this code location
                    _codeLocationRepository.RecordCodeLocationOnWorker(WorkerId, codelocation.Id);

                    // schedule an import
                    _jobRepository.ScheduleJob<ImportHistoryJob>(codelocation);

                    _jobRepository.CompleteJob(Id, WorkerId, new
                    {
                        localPath = result
                    });

                    return Task.FromResult<JobResult>(new JobSuccessResult(this));
                }
                catch (Exception e)
                {
                    return Task.FromResult<JobResult>(new JobFailureResult(e, this));
                }
            });
        }
        public static void BUYLCloneOrUpdateRepository()
        {
            if (!CheckForContentRepositoryDirectory())
            {
                //prg.ShowDialog();
                Directory.CreateDirectory(pathToLocalContentRepository);

                CloneOptions op = new CloneOptions();

                Repository.Clone(urlContentRepository, pathToLocalContentRepository, op);
                //prg.Close();
            }
            else
            {
                using (var repo = new Repository(pathToLocalContentRepository))
                {
                    Remote remote = repo.Network.Remotes["origin"];
                    FetchOptions op = new FetchOptions();
                    repo.Network.Fetch(remote);
                }
            }
        }
 public async Task<string> Clone(string url, string workingDirectory, CloneOptions options = null)
 {
     return await new Task<string>(() => Repository.Clone(url, workingDirectory, options));
 }
示例#13
0
        static void CloneRepository(string repositoryUrl, string gitDirectory, AuthenticationInfo authentication)
        {
            Credentials credentials = null;
            if (!string.IsNullOrWhiteSpace(authentication.Username) && !string.IsNullOrWhiteSpace(authentication.Password))
            {
                Logger.WriteInfo(string.Format("Setting up credentials using name '{0}'", authentication.Username));

                credentials = new UsernamePasswordCredentials
                {
                    Username = authentication.Username,
                    Password = authentication.Password
                };
            }

            Logger.WriteInfo(string.Format("Retrieving git info from url '{0}'", repositoryUrl));

            try
            {
                var cloneOptions = new CloneOptions
                {
                    Checkout = false,
                    CredentialsProvider = (url, usernameFromUrl, types) => credentials
                };
                var returnedPath = Repository.Clone(repositoryUrl, gitDirectory, cloneOptions);
                Logger.WriteInfo(string.Format("Returned path after repository clone: {0}", returnedPath));
            }
            catch (LibGit2SharpException ex)
            {
                var message = ex.Message;
                if (message.Contains("401"))
                {
                    throw new Exception("Unauthorised: Incorrect username/password");
                }
                if (message.Contains("403"))
                {
                    throw new Exception("Forbidden: Possbily Incorrect username/password");
                }
                if (message.Contains("404"))
                {
                    throw new Exception("Not found: The repository was not found");
                }

                throw new Exception("There was an unknown problem with the Git repository you provided", ex);
            }
        }
示例#14
0
        public GitRepository(string url, string repoName,
            bool copyIfNotLocal = true,
            string branch = null,
            NetworkCredential credentials = null)
        {
            Url = url;
            RepositoryName = repoName;
            Branch = branch ?? "master";
            Credentials = credentials;

            var localPath = Path.Combine(LocalRepositoryFolder, RepositoryName);
            IsLocal = Directory.Exists(localPath);
            CredentialsHandler = (_url, _user, _cred) => new UsernamePasswordCredentials()
            {
                Username = Credentials.UserName,
                Password = Credentials.Password
            };

            if (!IsLocal && copyIfNotLocal)
            {
                var cloneOptions = new CloneOptions()
                {
                    BranchName = Branch,
                    IsBare = false,
                    CredentialsProvider = CredentialsHandler
                };
                var path = Repository.Clone(Url, Path.Combine(LocalRepositoryFolder, RepositoryName), cloneOptions);
                IsLocal = true;
                LinkRepo();
            }
            else
                LinkRepo();
        }
示例#15
0
 private void setupOptions(string Username, SecureString SecurePassword, string RepoPath, string RepoUrl)
 {
     credentials = new SecureUsernamePasswordCredentials() { Username = Username, Password = SecurePassword };
     var credentialsProvider = new CredentialsHandler((_url, _user, _cred) => new SecureUsernamePasswordCredentials
     {
         Username = Username,
         Password = SecurePassword
     });
     fetchOptions = new FetchOptions() { CredentialsProvider = credentialsProvider };
     pullOptions = new PullOptions() { FetchOptions = fetchOptions };
     pushOptions = new PushOptions() { CredentialsProvider = credentialsProvider };
     cloneOptions = new CloneOptions() { CredentialsProvider = credentialsProvider };
     statusOptions = new StatusOptions() { ExcludeSubmodules = true, IncludeUnaltered = false };
 }
        public string RetrieveProject(string username, string password)
        {
            string baseRepositoryPath = Path.Combine(System.Web.Hosting.HostingEnvironment.MapPath("~/"),"GithubStaging");

            _absoluteRepositoryPath = Path.Combine(baseRepositoryPath, UserName, RepoName);

            // libgit2 requires the target directory to be empty
            if (Directory.Exists(_absoluteRepositoryPath))
            {
                DeleteReadOnlyDirectory(_absoluteRepositoryPath);
            }
            Directory.CreateDirectory(_absoluteRepositoryPath);

            //credentials provided
            if (!string.IsNullOrEmpty(username) || !string.IsNullOrEmpty(password))
            {
                CloneOptions cloneOptions = new CloneOptions();
                cloneOptions.CredentialsProvider = (url, fromUrl, types) => new UsernamePasswordCredentials()
                {
                    Username = username,
                    Password = password
                };
                Repository.Clone(_url, _absoluteRepositoryPath, cloneOptions);
            }
            else
            {
                //no credentials
                Repository.Clone(_url, _absoluteRepositoryPath);
            }

            return _absoluteRepositoryPath;
        }
        protected virtual bool Run() 
        {
            var currentDirectory = Directory.GetCurrentDirectory();
            var rootRepositoryDirectory = VersionResolver.GetRootRepositoryDirectoryOf(currentDirectory);
            Log($"{nameof(BaseGit)}.{nameof(Run)}: current directory = {currentDirectory}, root repository directory = {rootRepositoryDirectory}");
            
            var rawDependencies = JsonConvert.DeserializeObject<CompileDependencies>(File.ReadAllText(DependencyFile));
            var userDefinedDependencies = readUserDefinedDependencies();
            var userDefinedAuthentication = readUserDefinedAuth();
            var dependencies = MergeDependencies(rawDependencies, userDefinedDependencies, userDefinedAuthentication);

            Names = dependencies.Select(d => $@"{d.OutputFolder}\build.xml").ToArray();

            try
            {
                IndentLevel++;

                using (var myRepository = new Repository(rootRepositoryDirectory.FullName))
                {
                    foreach (var dependency in dependencies)
                    {
                        if (dependency.UseGit)
                        {
                            var cloneOptions = new CloneOptions()
                            {
                                CredentialsProvider = (_url, _user, _cred) => dependency.GetCredentials(Authentication)
                            };

                            if (dependency.Branch == "autoversioning")
                                HandleAutoVersioning(myRepository, rawDependencies.ShortName, dependency, cloneOptions);
                            else
                                HandleFixedVersioning(dependency, cloneOptions);
                        }
                        else
                            Log($"Dependency {dependency} does not use a remote repository");
                    }
                }
            }
            finally
            {
                IndentLevel--; 
            }

            return true;
        }
示例#18
0
        private string GetGitInfoFromUrl(Context context, string gitDirectory)
        {
            gitDirectory = Path.Combine(gitDirectory, ".git");
            if (Directory.Exists(gitDirectory))
            {
                Log.Info("Deleting existing .git folder from '{0}' to force new checkout from url", gitDirectory);

                DeleteHelper.DeleteGitRepository(gitDirectory);
            }

            Log.Info("Retrieving git info from url '{0}'", context.TargetUrl);

            Credentials credentials = null;
            var authentication = context.Authentication;
            if (!string.IsNullOrWhiteSpace(authentication.Username) && !string.IsNullOrWhiteSpace(authentication.Password))
            {
                Log.Info("Setting up credentials using name '{0}'", authentication.Username);

                credentials = new UsernamePasswordCredentials
                {
                    Username = authentication.Username,
                    Password = authentication.Password
                };
            }

            var cloneOptions = new CloneOptions
            {
                Checkout = false,
                IsBare = true,
                CredentialsProvider = (url, username, supportedTypes) => credentials
            };

            Repository.Clone(context.TargetUrl, gitDirectory, cloneOptions);

            if (!string.IsNullOrWhiteSpace(context.TargetBranch))
            {
                using (var repository = new Repository(gitDirectory))
                {
                    Reference newHead = null;

                    var localReference = GetLocalReference(repository, context.TargetBranch);
                    if (localReference != null)
                    {
                        newHead = localReference;
                    }

                    if (newHead == null)
                    {
                        var remoteReference = GetRemoteReference(repository, context.TargetBranch, context.TargetUrl);
                        if (remoteReference != null)
                        {
                            repository.Network.Fetch(context.TargetUrl, new[]
                            {
                                string.Format("{0}:{1}", remoteReference.CanonicalName, context.TargetBranch)
                            });

                            newHead = repository.Refs[string.Format("refs/heads/{0}", context.TargetBranch)];
                        }
                    }

                    if (newHead != null)
                    {
                        Log.Info("Switching to branch '{0}'", context.TargetBranch);

                        repository.Refs.UpdateTarget(repository.Refs.Head, newHead);
                    }
                }
            }

            return gitDirectory;
        }
        protected virtual void HandleAutoVersioning(Repository myRepository, string myShortName, Dependency dependency, CloneOptions cloneOptions)
        {
            if (!string.IsNullOrEmpty(dependency.Commit))
                throw new InvalidOperationException($"Dependency {dependency}: autoversioning: definition is incoherent: Branch = '{dependency.Branch}' and a Commit = '{dependency.Commit}' => you can't have both set!");

            if (Directory.Exists(dependency.OutputFolder))
            {
                Log($"Dependency {dependency}: autoversioning: output folder already exists: removing...");
                new DirectoryInfo(dependency.OutputFolder).ForceDelete();
            }

            Log($"Dependency {dependency}: autoversioning: cloning default branch of '{dependency.Remote}' into '{dependency.OutputFolder}'");
            Repository.Clone(dependency.Remote, dependency.OutputFolder, cloneOptions);

            try
            {
                IndentLevel++;

                using (var otherRepository = new Repository(dependency.OutputFolder))
                {
                    otherRepository.CheckoutAllRemoteBranches();
                    VersionResolver.CheckoutBranchInDependencyRepository(otherRepository, myRepository, myShortName, this);
                }
            }
            finally
            {
                IndentLevel--; 
            }
        }
示例#20
0
        public static DirectoryPath GitClone(
            this ICakeContext context,
            string sourceUrl,
            DirectoryPath workDirectoryPath,
            string username,
            string password
            )
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (string.IsNullOrWhiteSpace(sourceUrl))
            {
                throw new ArgumentNullException(nameof(sourceUrl));
            }

            if (string.IsNullOrWhiteSpace(username))
            {
                throw new ArgumentNullException(nameof(username));
            }

            if (string.IsNullOrWhiteSpace(password))
            {
                throw new ArgumentNullException(nameof(password));
            }

            if (workDirectoryPath == null)
            {
                throw new ArgumentNullException(nameof(workDirectoryPath));
            }

            var workFullDirectoryPath = workDirectoryPath.MakeAbsolute(context.Environment);

            if (!context.FileSystem.Exist(workFullDirectoryPath))
            {
                throw new DirectoryNotFoundException($"Failed to find workDirectoryPath: {workFullDirectoryPath}");
            }

            var options = new CloneOptions
            {
                CredentialsProvider =
                    (url, user, cred) => new UsernamePasswordCredentials {Username = username, Password = password}
            };

            return Repository.Clone(sourceUrl, workFullDirectoryPath.FullPath, options);
        }
        protected virtual void HandleFixedVersioning(Dependency dependency, CloneOptions cloneOptions)
        {
            if (!string.IsNullOrEmpty(dependency.Branch) && !string.IsNullOrEmpty(dependency.Commit))
                throw new InvalidOperationException($"Dependency {dependency}: fixed versioning: definition is incoherent: Branch = '{dependency.Branch}' != '' and Commit = '{dependency.Commit}' != '' => you can't have both set!");

            if (!Directory.Exists(dependency.OutputFolder))
            {
                Log($"Dependency {dependency}: fixed versioning: cloning fixed branch '{dependency.Branch}' of '{dependency.Remote}' into '{dependency.OutputFolder}'...");
                cloneOptions.BranchName = dependency.Branch;
                Repository.Clone(dependency.Remote, dependency.OutputFolder, cloneOptions);
            }
            else if (Pull)
            {
                Log($"Dependency {dependency}: fixed versioning: repository '{dependency.Remote}' already cloned in '{dependency.OutputFolder}'");

                try
                {
                    IndentLevel++;

                    using (var otherRepository = new Repository(dependency.OutputFolder))
                    {
                        otherRepository.CheckoutAllRemoteBranches();

                        if (!string.IsNullOrEmpty(dependency.Commit))
                            HandleFixedVersioning_Commit(dependency, otherRepository);
                        else
                            HandleFixedVersioning_Branch(dependency, otherRepository);
                    }
                }
                finally
                {
                    IndentLevel--; 
                }
            }
        }
示例#22
0
        private void DownloadAddon()
        {
            bool updated = false;
            bool cloned = false;

            if (!Directory.Exists(info.packedPath))
            {
                Directory.CreateDirectory(info.packedPath);
            }

            if (Directory.Exists(info.dlPath) && Repository.IsValid(info.dlPath))
            {
                using (Repository repo = new Repository(info.dlPath))
                {
                    RepositoryStatus status = repo.RetrieveStatus();

                    string commit = repo.Head.Tip.Id.Sha;

                    // reset local changes
                    if (status.IsDirty)
                    {
                        repo.Reset(ResetMode.Hard);
                    }

                    // fetch & merge from origin
                    repo.Network.Fetch(repo.Network.Remotes["origin"]);
                    repo.MergeFetchedRefs(new Signature("meldii", "*****@*****.**", new DateTimeOffset()), new MergeOptions());

                    // updated
                    if (!repo.Head.Tip.Id.Sha.Equals(commit))
                    {
                        updated = true;
                    }
                }
            }
            else
            {
                if (Directory.Exists(info.dlPath))
                {
                    ForceDeleteDirectory(info.dlPath);
                }

                CloneOptions co = new CloneOptions();
                co.BranchName = info.branch;
                Repository.Clone(info.url, info.dlPath, co);
                updated = true;
                cloned = true;
            }

            //Pack & ship it
            if (updated)
            {
                if (File.Exists(info.packedFile))
                {
                    File.Delete(info.packedFile);
                }

                ZipFile zip = new ZipFile(info.packedFile);
                foreach (string file in Directory.EnumerateFiles(info.dlPath, "*.*", SearchOption.AllDirectories))
                {
                    string rPath = file.Replace(info.dlPath, "").TrimStart(new char[] { '\\', '/' });
                    if (!rPath.StartsWith(".git", StringComparison.CurrentCultureIgnoreCase) && !rPath.Equals("README.md", StringComparison.CurrentCultureIgnoreCase))
                    {
                        string[] split = rPath.Split(new char[] { '\\', '/' });
                        string zipPath = split.Length == 1 ? "" : string.Join("\\", split, 0, split.Length - 1);

                        zip.AddFile(file, zipPath);
                    }

                }
                zip.Save();
            }

            if (cloned)
            {
                _Copy(Path.Combine(MeldiiSettings.Self.AddonLibaryPath, info.repoName) + ".zip", info.packedFile);
            }
        }
示例#23
0
    private static void RunLibGit2SharpCode(TextWriter log)
    {
      // TODO: enter your VSTS alternate credentials
      string userName = "";
      string password = "";

      // TODO: enter your VSTS account name
      string accountRoot = "yourroot";

      // TODO: enter the name of a clean VSTS team project 
      // with an emptry default Git repo
      string teamProjectName = "yourteamproject";

      try
      {
        var co = new CloneOptions();
        co.CredentialsProvider = (_url, _user, _cred) =>
          new UsernamePasswordCredentials
          {
            Username = userName,
            Password = password
          };

        string reposRoot = Path.Combine(
          Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
          "repos");
        if (Directory.Exists(reposRoot))
        {
          // directory exists, delete
          log.WriteLine("Cleaning reposRoot: " + reposRoot);
          DeleteReadOnlyDirectory(reposRoot);
        }
        string repoRoot = Path.Combine(reposRoot, teamProjectName);

        string accountUrl = string.Format("https://{0}.visualstudio.com/DefaultCollection", accountRoot);

        Repository.Clone(accountUrl + "/_git/" + teamProjectName, repoRoot, co);
        log.WriteLine("Clone Done!");

        using (Repository repo = new Repository(repoRoot))
        {
          log.WriteLine("Repo aquired");

          //// Write file
          string newFilePath = System.IO.Path.Combine(repoRoot, "test.txt");
          System.IO.File.WriteAllText(newFilePath, "Some great text.");
          log.WriteLine("New text file written");

          log.WriteLine("repo.RetrieveStatus()");
          var status = repo.RetrieveStatus();
          foreach (var item in status)
          {
            if (item.State == FileStatus.Untracked)
            {
              // *** Warning ***
              // this line of code causes the Azure Web Job to blow up
              repo.Index.Add(item.FilePath);
              log.WriteLine(item.FilePath + " added to index");
            }
          }
        }
      }
      catch (Exception ex)
      {
        log.WriteLine("Failure in LoadCodeIntoGitRepo");
        log.WriteLine(ex.ToString());
      }
    }
        private void CloneRepositories()
        {
            string repoDir = outputDir + @"\BitBucket Repositories\" + requestedAcct + @"\";
            if (Directory.Exists(repoDir))
            {
                DeleteFolderPath(repoDir);
            }


            var creds = new CloneOptions()
            {
                CredentialsProvider = (_url, _user, _pw) => new UsernamePasswordCredentials
                {
                    Username = bbName,
                    Password = bbPassword
                }
            };

            foreach (string repo in repositories)
            {
                string url = @"https://bitbucket.org/" + requestedAcct + "/" + repo;
                string cloneDir = repoDir + repo;

                try
                {
                    LibGit2Sharp.Repository.Clone(url, cloneDir, creds);
                }
                catch
                {
                    string msg = "Handled LibGit2Sharp exception";
                    MessageBox.Show(msg);
                }
            }
        }