text
stringlengths 5
22M
| id
stringlengths 12
177
| metadata
dict | __index_level_0__
int64 0
1.37k
|
---|---|---|---|
Archai Documentation
====================
**Archai** is a Neural Architecture Search (NAS) framework built upon PyTorch. It provides a comprehensive solution for automating the process of finding the optimal architecture for deep learning models, making it easier for researchers and practitioners to achieve state-of-the-art results. First launched as an open-source project in 2020, Archai has made impactful progress by forming a positive feedback loop between the engineering and research aspects.
It has innovated on both search algorithms and search spaces, explored ideas on zero-cost proxies of architecture accuracy and in very recent work explored novel more efficient alternatives to the ubiquitious attention operator which is now informing next-generation search-space design. Additionally, it offers the following advantages:
* 🔬 Easy mix-and-match between different algorithms;
* 📈 Self-documented hyper-parameters and fair comparison;
* ⚡ Extensible and modular to allow rapid experimentation;
* 📂 Powerful configuration system and easy-to-use tools.
Citing Archai
-------------
If you use Archai in a scientific publication, please consider citing it:
.. code-block:: latex
@misc{Archai:22,
title=Archai: Platform for Neural Architecture Search,
url=https://www.microsoft.com/en-us/research/project/archai-platform-for-neural-architecture-search,
journal=Microsoft Research,
year=2022,
month=Jul
}
.. toctree::
:hidden:
:maxdepth: 2
:caption: Getting Started
Installation <getting_started/installation>
Package Structure <getting_started/package_structure>
Quick Start <getting_started/quick_start>
Notebooks <getting_started/notebooks>
.. toctree::
:hidden:
:maxdepth: 2
:caption: Advanced Guide
Cloud-Based Search <advanced_guide/cloud>
.. toctree::
:hidden:
:maxdepth: 2
:caption: Contributing
First Time Contributor <contributing/first_contribution>
Documentation <contributing/documentation>
Unit Tests <contributing/unit_tests>
.. toctree::
:hidden:
:maxdepth: 2
:caption: Support
Frequently Asked Questions <support/faq>
Contact <support/contact>
Copyright <support/copyright>
.. toctree::
:hidden:
:maxdepth: 2
:caption: Reference
API <reference/api>
Roadmap <reference/roadmap>
Changelog <reference/changelog>
|
archai/docs/index.rst/0
|
{
"file_path": "archai/docs/index.rst",
"repo_id": "archai",
"token_count": 683
}
| 341 |
Predictors
==========
DNN Ensemble
------------
.. automodule:: archai.discrete_search.predictors.dnn_ensemble
:members:
:undoc-members:
|
archai/docs/reference/api/archai.discrete_search.predictors.rst/0
|
{
"file_path": "archai/docs/reference/api/archai.discrete_search.predictors.rst",
"repo_id": "archai",
"token_count": 54
}
| 342 |
DARTS
=====
Bi-Level Architecture Trainer
------------------------------
.. automodule:: archai.supergraph.algos.darts.bilevel_arch_trainer
:members:
:undoc-members:
Bi-Level Optimizer
------------------
.. automodule:: archai.supergraph.algos.darts.bilevel_optimizer
:members:
:undoc-members:
Bi-Level Optimizer (Slow)
-------------------------
.. automodule:: archai.supergraph.algos.darts.bilevel_optimizer_slow
:members:
:undoc-members:
Experiment Runner
-----------------
.. automodule:: archai.supergraph.algos.darts.darts_exp_runner
:members:
:undoc-members:
Model Description Builder
-------------------------
.. automodule:: archai.supergraph.algos.darts.darts_model_desc_builder
:members:
:undoc-members:
Mixed Operators
---------------
.. automodule:: archai.supergraph.algos.darts.mixed_op
:members:
:undoc-members:
|
archai/docs/reference/api/archai.supergraph.algos.darts.rst/0
|
{
"file_path": "archai/docs/reference/api/archai.supergraph.algos.darts.rst",
"repo_id": "archai",
"token_count": 308
}
| 343 |
Utilities
=========
Augmented Searcher
------------------
.. automodule:: archai.supergraph.utils.augmented_searcher
:members:
:undoc-members:
Augmented Trainer
-----------------
.. automodule:: archai.supergraph.utils.augmented_trainer
:members:
:undoc-members:
Checkpoint
----------
.. automodule:: archai.supergraph.utils.checkpoint
:members:
:undoc-members:
Heatmap
-------
.. automodule:: archai.supergraph.utils.heatmap
:members:
:undoc-members:
Metrics
-------
.. automodule:: archai.supergraph.utils.metrics
:members:
:undoc-members:
Multi-Optimizer
---------------
.. automodule:: archai.supergraph.utils.multi_optim
:members:
:undoc-members:
Tester
------
.. automodule:: archai.supergraph.utils.tester
:members:
:undoc-members:
Trainer
-------
.. automodule:: archai.supergraph.utils.trainer
:members:
:undoc-members:
|
archai/docs/reference/api/archai.supergraph.utils.rst/0
|
{
"file_path": "archai/docs/reference/api/archai.supergraph.utils.rst",
"repo_id": "archai",
"token_count": 328
}
| 344 |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
from typing import List, Optional
import torch
from lm_eval.base import BaseLM
from lm_eval_harness.utils.multiple_token_stopping_criteria import (
MultipleTokenStoppingCriteria,
)
from lm_eval_harness.utils.request_factory import Request
from tqdm import tqdm
from transformers.generation.stopping_criteria import StoppingCriteriaList
from transformers.tokenization_utils import PreTrainedTokenizer
class HFEvalModel(BaseLM):
def __init__(
self,
model: torch.nn.Module,
tokenizer: PreTrainedTokenizer,
force_attention_mask: Optional[bool] = False,
max_generated_tokens: Optional[int] = 256,
) -> None:
super().__init__()
self._device = torch.device("cpu")
if torch.cuda.is_available():
self._device = torch.device("cuda")
self.model = model.to(self.device)
self.tokenizer = tokenizer
self.tokenizer.add_special_tokens({"pad_token": "[PAD]"})
self.force_attention_mask = force_attention_mask
self.max_generated_tokens = max_generated_tokens
@property
def eot_token_id(self) -> int:
return self.tokenizer.eos_token_id
@property
def max_length(self) -> int:
try:
return self.model.config.n_ctx
except AttributeError:
return self.model.config.max_position_embeddings
@property
def max_gen_toks(self) -> int:
return self.max_generated_tokens
@property
def batch_size(self) -> int:
return 1
@property
def device(self) -> torch.device:
return self._device
def tok_encode(self, string: str) -> List[int]:
return self.tokenizer.encode(string, add_special_tokens=False)
def tok_decode(self, tokens: List[int]) -> str:
return self.tokenizer.decode(tokens)
def _model_call(self, inps: torch.Tensor) -> torch.Tensor:
inps = inps.to(self.device)
kwargs = {}
if self.force_attention_mask:
kwargs["attention_mask"] = torch.zeros(inps.shape, dtype=torch.long, device=inps.device)
with torch.no_grad():
return self.model(inps, **kwargs)[0]
def _model_generate(self, context: str, max_length: int, eos_token_id: int) -> str:
return self.model.generate(context, max_length=max_length, eos_token_id=eos_token_id, do_sample=False)
def generate(self, requests: List[Request]) -> List[str]:
res = []
kwargs = {}
for context, stop_tokens, do_sample, temperature, top_p, max_new_tokens in tqdm(requests):
if not context:
context = self.eos_token
# Encodes the context and defines number of tokens to be
# removed when generation ends (default = 1)
input_ids = self.tokenizer(context, return_tensors="pt")["input_ids"].to(self.device)
n_removal_tokens = 1
if stop_tokens:
# Encodes the stop-tokens and defines the number of tokens to be
# removed as largest stop-token
encoded_stop_tokens = self.tokenizer(
stop_tokens,
padding="longest",
add_special_tokens=False,
return_attention_mask=False,
return_tensors="pt",
)["input_ids"].to(self.device)
n_removal_tokens = encoded_stop_tokens.shape[-1]
# Defines the stopping criteria
kwargs["stopping_criteria"] = StoppingCriteriaList([MultipleTokenStoppingCriteria(encoded_stop_tokens)])
# Generates the tokens and removes generated stop-tokens
generated_tokens = self.model.generate(
input_ids,
pad_token_id=self.eot_token_id,
do_sample=do_sample,
temperature=temperature,
top_p=top_p,
max_new_tokens=max_new_tokens,
**kwargs
).squeeze(0)
generated_tokens = generated_tokens[:-n_removal_tokens]
res.append(self.tok_decode(generated_tokens))
return res
|
archai/research/lm_eval_harness/lm_eval_harness/lm_eval_hf_model.py/0
|
{
"file_path": "archai/research/lm_eval_harness/lm_eval_harness/lm_eval_hf_model.py",
"repo_id": "archai",
"token_count": 1949
}
| 345 |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import argparse
import numpy as np
import torch
from archai.onnx.onnx_loader import load_from_onnx
def parse_args():
parser = argparse.ArgumentParser(description="Validates past key/values with an ONNX model.")
parser.add_argument("onnx_model_path", type=str, help="Path to the ONNX model file.")
parser.add_argument("-nh", "--n_head", type=int, default=12, help="Number of attention heads.")
parser.add_argument("-dh", "--d_head", type=int, default=64, help="Dimension of attention head.")
parser.add_argument("-bs", "--batch_size", type=int, default=1, help="Size of the batch.")
parser.add_argument("-sl", "--seq_len", type=int, default=32, help="Sequence length.")
parser.add_argument("-psl", "--past_seq_len", type=int, default=32, help="Past key/values sequence length.")
parser.add_argument("-npv", "--n_past_values", type=int, default=2, help="Number of past key/values.")
parser.add_argument("-nl", "--n_layers", type=int, default=12, help="Number of layers.")
parser.add_argument("-nt", "--n_tokens", type=int, default=10000, help="Number of tokens for sampling.")
parser.add_argument("-nr", "--n_runs", type=int, default=100, help="Number of comparisons.")
parser.add_argument("-nti", "--new_token_id", type=int, default=6, help="Identifier of token to be predicted.")
args = parser.parse_args()
return args
if __name__ == "__main__":
args = parse_args()
accuracy = 0.0
for i in range(args.n_runs):
torch.manual_seed(i)
np.random.seed(i)
model_onnx = load_from_onnx(args.onnx_model_path)
inputs = {"input_ids": np.random.randint(0, args.n_tokens, (args.batch_size, args.seq_len), dtype=np.int64)}
for i in range(args.n_layers):
key = f"past_{i}"
inputs[key] = np.zeros(
(args.n_past_values, args.batch_size, args.n_head, args.past_seq_len, args.d_head), dtype=np.float32
)
# 1st inference (full pass with initial inputs)
outputs = model_onnx.run(None, inputs)
# 2nd inference (partial pass with only `new_token_id`)
inputs_p = {"input_ids": np.array([[args.new_token_id]], dtype=np.int64)}
for i in range(args.n_layers):
key = f"past_{i}"
inputs_p[key] = outputs[i + 1]
outputs_partial = model_onnx.run(None, inputs_p)
# 3rd inference (full pass with initial inputs and `new_token_id`)
inputs["input_ids"] = np.expand_dims(np.append(inputs["input_ids"], args.new_token_id), 0)
outputs_full = model_onnx.run(None, inputs)
accuracy += np.argmax(outputs_partial[0]) == np.argmax(outputs_full[0])
print(f"Partial pass (with past key/value) sample token: {np.argmax(outputs_partial[0])}")
print(f"Full pass (without past key/value) sample token: {np.argmax(outputs_full[0])}")
accuracy /= args.n_runs
print(f"Acc: {accuracy}")
|
archai/scripts/onnx/validate_past_key_values.py/0
|
{
"file_path": "archai/scripts/onnx/validate_past_key_values.py",
"repo_id": "archai",
"token_count": 1229
}
| 346 |
import argparse
import os
from collections import Counter
import numpy as np
from archai.common import utils
class _Corpus:
def __init__(self, word2idx, path):
self.word2idx = word2idx
self.train = self.encode_file(path % "train")
self.valid = self.encode_file(path % "valid")
self.test = self.encode_file(path % "test")
def encode_file(self, path):
tokens = []
with open(path, "r", encoding="utf-8") as f:
for line in f:
words = line.split() + ["<eos>"]
for w in words:
tokens.append(self.word2idx[w])
return np.array(tokens)
def main():
parser = argparse.ArgumentParser(description="Pytorch cifar training")
parser.add_argument("--datadir", default="~/dataroot/textpred/wikitext-103") # .token files from original dataset
parser.add_argument(
"--cachedir", default="~/dataroot/textpred/wikitext-103-sorted-vocab"
) # this should have 'wikitext-103-sorted_vocab.npy' file
args = parser.parse_args()
args.datadir = utils.full_path(args.datadir)
args.cachedir = utils.full_path(args.cachedir)
# For compatibility, we use a precomputed vocab sorted from most to least occurence in the training set
sorted_vocab_filepath = os.path.join(args.cachedir, "sorted_vocab.npy")
idx2word = np.load(sorted_vocab_filepath, allow_pickle=True)
word2idx = {w: i for i, w in enumerate(idx2word)}
assert len(word2idx) == 267735
# Might take 5-10 minutes to run
corpus = _Corpus(word2idx, os.path.join(args.datadir, "wiki.%s.tokens"))
train_counts = Counter(corpus.train)
for i, (token, count) in enumerate(train_counts.most_common()): # Check that our vocab is indeed sorted
assert count == train_counts[i]
for k in "train", "valid", "test":
sorted_file_path = os.path.join(args.cachedir, "sorted_" + k + ".npy")
np.save(sorted_file_path, getattr(corpus, k).astype(np.int32))
if __name__ == "__main__":
main()
|
archai/scripts/supergraph/download_datasets/wikitext103_setup.py/0
|
{
"file_path": "archai/scripts/supergraph/download_datasets/wikitext103_setup.py",
"repo_id": "archai",
"token_count": 873
}
| 347 |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
from archai.common.common import common_init
from archai.common.model_summary import summary
from archai.supergraph.algos.petridish.petridish_model_desc_builder import (
PetridishModelBuilder,
)
from archai.supergraph.nas.model import Model
from archai.supergraph.nas.model_desc import ModelDesc
conf = common_init(
config_filepath="confs/petridish_cifar.yaml", param_args=["--common.experiment_name", "petridish_run2_seed42_eval"]
)
conf_eval = conf["nas"]["eval"]
conf_model_desc = conf_eval["model_desc"]
conf_model_desc["n_cells"] = 14
template_model_desc = ModelDesc.load("$expdir/final_model_desc.yaml")
model_builder = PetridishModelBuilder()
model_desc = model_builder.build(conf_model_desc, template=template_model_desc)
mb = PetridishModelBuilder()
model = Model(model_desc, droppath=False, affine=False)
summary(model, [64, 3, 32, 32])
exit(0)
|
archai/scripts/supergraph/performance/model_size.py/0
|
{
"file_path": "archai/scripts/supergraph/performance/model_size.py",
"repo_id": "archai",
"token_count": 325
}
| 348 |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
[flake8]
max-line-length = 120
extend-ignore = E111, E203, E402, E501, E721, E722, E741, F401, F403, F405, F407, W503, W504, W605
max-complexity = 12
[isort]
profile = black
[metadata]
description-file = README.md
|
archai/setup.cfg/0
|
{
"file_path": "archai/setup.cfg",
"repo_id": "archai",
"token_count": 111
}
| 349 |
# Azure Setup
This Azure code connects to an Azure Storage account by a connection string setup in an environment variable named
`MODEL_STORAGE_CONNECTION_STRING`.
There is a handy [setup.ps1](../docker/quantizer/setup.ps1) powershell script that will setup a new Azure Storage
account and print this connection string key for you using the Azure CLI.
You can get the connection string from your Azure Storage account under `Access Keys` and `Show Keys` and copy the one
named `Connection string`.
In Linux you should use double quotes around the connection string like this:
```
export MODEL_STORAGE_CONNECTION_STRING="DefaultEndpointsProtocol=...EndpointSuffix=core.windows.net"
```
You'll use it a lot so it is handy if you put it in your `~/.profile`.
Then you can use the scripts here as follows:
1. `upload.py` - upload a new model, it will allocate a friendly name for your model if you
can't think of one. All the charts and graphs and tables are more readable if you stick with
the allocated friendly names. But the actual model file names can be whatever large name you need.
1. `download.py` - can download all azure blob assets associated with the given friendly name.
This can include the .onnx model, all test results, and converted .dlc models.
1. `priority_queue.py` - is just a helper class.
1. `reset.py` - sometimes you want to re-test a model if something went wrong, this can reset
the `state` of a job by it's friendly name.
1. `status.py` - can download all the status info from the Azure Table in .csv format.
1. `delete.py` - sometimes a model turns out to be junk, so you can delete a row in the table and it's
associated azure blob folder with this handy script.
1. `runner.py` - this is the magic script that runs everything. See below.
## Runner
Then to get the ball rolling create a temp folder and run this:
```
mkdir -p ~/experiment
python ~/git/archai/tasks/face_Segmentation/aml/azure/runner.py --working ~/experiment
```
This will monitor the Azure blob store for new work to do, and run those jobs in priority order. If you also provide a
`--device` option pointing to the `adb device` for a Qualcomm 888 Dev Board then it will also run the quantized models
on that device and report the performance and F1 score results. If the row in the azure table contains the property
`benchmark_only` equal to 1, then it will skip computing any F1 scores.
If you setup a quantization only runner in the cloud using the `docker/quantizer` image, you can pass
`--no_quantization` argument when you have a `--device` so that the local runs do not do quantization. This will stop
your linux machine from getting overloaded with quantization work so it can focus on managing the SNPE device workloads.
|
archai/tasks/face_segmentation/aml/azure/readme.md/0
|
{
"file_path": "archai/tasks/face_segmentation/aml/azure/readme.md",
"repo_id": "archai",
"token_count": 729
}
| 350 |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import argparse
import os
import sys
import glob
from shutil import copyfile, rmtree
def cleanup_results(dataset, output_dir):
""" cleans up a folder containing Results* folders downloaded from device
and renames the output images to match the input image names so that
collect_metrics can work on the folder """
test_size = 0
result_dirs = os.listdir(output_dir)
for name in result_dirs:
if name.startswith('Result_'):
test_size += 1
print(f"Found {test_size} Result_* folders")
all_seg_files = sorted(glob.glob(os.path.join(dataset, '*_seg.png')))
if len(all_seg_files) < test_size:
print(f"### not enough *_seg.png files found in {dataset}")
sys.exit(1)
test_files = all_seg_files[len(all_seg_files) - test_size:]
raw_file_name = 'output.raw'
index = 0
for name in test_files:
name = os.path.basename(name).split('_')[0]
result = f"Result_{index}"
if result in result_dirs:
raw_file = os.path.join(output_dir, result, raw_file_name)
if not os.path.isfile(raw_file):
raw_file_name = os.listdir(os.path.join(output_dir, result))[0]
raw_file = os.path.join(output_dir, result, raw_file_name)
output_file = os.path.join(output_dir, name + '.raw')
print(f"{raw_file} ===> {output_file}")
copyfile(raw_file, output_file)
rmtree(os.path.join(output_dir, result))
index += 1
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Check the outputs from the device')
parser.add_argument('--input', help='Location of the original input images ' +
'(defaults to INPUT_DATASET environment variable)')
parser.add_argument('--output', '-o', help='Location of the folder containing Result* folders')
args = parser.parse_args()
dataset = args.input
if not dataset:
dataset = os.getenv("INPUT_DATASET")
if not dataset:
print("please provide --input or set your INPUT_DATASET environment vairable")
sys.exit(1)
output = args.output
if not os.path.isdir(output):
print("--output dir not found")
sys.exit(1)
cleanup_results(dataset, output)
print("Done")
|
archai/tasks/face_segmentation/aml/snpe/cleanup_results.py/0
|
{
"file_path": "archai/tasks/face_segmentation/aml/snpe/cleanup_results.py",
"repo_id": "archai",
"token_count": 995
}
| 351 |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import subprocess
from threading import Thread, Lock
class Shell:
def __init__(self):
self.output = ''
self.lock = Lock()
self.verbose = False
def run(self, cwd, command, print_output=True):
self.output = ''
self.verbose = print_output
with subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=0,
universal_newlines=True, cwd=cwd, shell=True) as proc:
stdout_thread = Thread(target=self.logstream, args=(proc.stdout,))
stderr_thread = Thread(target=self.logstream, args=(proc.stderr,))
stdout_thread.start()
stderr_thread.start()
while stdout_thread.is_alive() or stderr_thread.is_alive():
pass
proc.wait()
if proc.returncode:
words = command.split(' ')
print("### command {} failed with error code {}".format(words[0], proc.returncode))
raise Exception(self.output)
return self.output
def logstream(self, stream):
try:
while True:
out = stream.readline()
if out:
self.log(out)
else:
break
except Exception as ex:
msg = "### Exception: {}".format(ex)
self.log(msg)
def log(self, msg):
self.lock.acquire()
try:
msg = msg.rstrip('\r\n')
self.output += msg + '\r\n'
if self.verbose:
print(msg)
finally:
self.lock.release()
|
archai/tasks/face_segmentation/aml/util/shell.py/0
|
{
"file_path": "archai/tasks/face_segmentation/aml/util/shell.py",
"repo_id": "archai",
"token_count": 873
}
| 352 |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
from functools import partial
from itertools import chain
import torch
from torch import nn
class Conv2dSamePadding(nn.Conv2d):
__doc__ = nn.Conv2d.__doc__
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
pad_shape = tuple(chain(*[
[k // 2 + (k - 2 * (k // 2)) - 1, k // 2]
for k in self.kernel_size[::-1]
]))
self.pad = nn.ZeroPad2d(pad_shape)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self._conv_forward(self.pad(x), self.weight, self.bias)
class ReluConv2d(nn.Module):
def __init__(self, in_channels: int, out_channels: int,
kernel_size: int = 3, stride: int = 1,
bias: bool = False, **kwargs):
super().__init__()
self.conv = Conv2dSamePadding(
in_channels, out_channels, kernel_size=kernel_size,
stride=stride, bias=bias
)
self.bn = nn.BatchNorm2d(out_channels)
self.act = nn.ReLU()
def forward(self, x: torch.Tensor):
return self.act(self.bn(self.conv(x)))
OPS = {
'conv3x3': partial(ReluConv2d, kernel_size=3),
'conv5x5': partial(ReluConv2d, kernel_size=5),
'conv7x7': partial(ReluConv2d, kernel_size=7),
}
|
archai/tasks/face_segmentation/search_space/ops.py/0
|
{
"file_path": "archai/tasks/face_segmentation/search_space/ops.py",
"repo_id": "archai",
"token_count": 633
}
| 353 |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import math
import os
from argparse import ArgumentParser
from datetime import datetime
from pathlib import Path
import pandas as pd
import yaml
from overrides.overrides import overrides
from archai.common.common import logger
from archai.discrete_search.algos.evolution_pareto import EvolutionParetoSearch
from archai.discrete_search.api.model_evaluator import ModelEvaluator
from archai.discrete_search.api.search_objectives import SearchObjectives
from archai.discrete_search.evaluators.ray import RayParallelEvaluator
import train as model_trainer
from dataset import FaceLandmarkDataset
from latency import AvgOnnxLatency
from search_space import ConfigSearchSpaceExt
class ValidationErrorEvaluator(ModelEvaluator):
def __init__(self, args) -> None:
self.args = args
@overrides
def evaluate(self, model, dataset_provider, budget=None) -> float:
logger.info(f"evaluating {model.archid}")
val_error = model_trainer.train(self.args, model.arch)
if math.isnan(val_error):
logger.info(
f"Warning: model {model.archid} has val_error NaN. Set to 10000.0 to avoid corrupting the Pareto front."
)
val_error = 10000.0
return val_error
class OnnxLatencyEvaluator(ModelEvaluator):
def __init__(self, args) -> None:
self.args = args
self.latency_evaluator = AvgOnnxLatency(
input_shape=(1, 3, 128, 128),
num_trials=self.args.num_latency_measurements,
num_input=self.args.num_input_per_latency_measurement,
)
@overrides
def evaluate(self, model, dataset_provider, budget=None) -> float:
return self.latency_evaluator.evaluate(model)
class SearchFaceLandmarkModels:
def __init__(self) -> None:
super().__init__()
config_parser = ArgumentParser(conflict_handler="resolve", description="NAS for Facial Landmark Detection.")
config_parser.add_argument(
"--config", required=True, type=Path, help="YAML config file specifying default arguments"
)
parser = ArgumentParser(conflict_handler="resolve", description="NAS for Facial Landmark Detection.")
parser.add_argument("--data_path", required=False, type=Path)
parser.add_argument("--output_dir", required=True, type=Path)
parser.add_argument("--num_jobs_per_gpu", required=False, type=int, default=1)
def _parse_args_from_config(parser_to_use):
args_config, remaining = config_parser.parse_known_args()
if args_config.config:
with open(args_config.config, "r") as f:
cfg = yaml.safe_load(f)
# The usual defaults are overridden if a config file is specified.
parser_to_use.set_defaults(**cfg)
# The parser to be used parses the rest of the known command line args.
args, _ = parser_to_use.parse_known_args(remaining)
return args
# parse twice to get the search args and trainer args
self.search_args = _parse_args_from_config(parser)
self.trainer_args = _parse_args_from_config(model_trainer.get_args_parser())
def search(self):
dataset = FaceLandmarkDataset(self.trainer_args.data_path)
ss = ConfigSearchSpaceExt(self.search_args, num_classes=dataset.num_landmarks)
search_objectives = SearchObjectives()
search_objectives.add_objective(
"Onnx_Latency_(ms)", OnnxLatencyEvaluator(self.search_args), higher_is_better=False, compute_intensive=False
)
search_objectives.add_objective(
"Partial_Training_Validation_Error",
RayParallelEvaluator(
ValidationErrorEvaluator(self.trainer_args),
num_gpus=1.0 / self.search_args.num_jobs_per_gpu,
max_calls=1,
),
higher_is_better=False,
compute_intensive=True,
)
algo = EvolutionParetoSearch(
search_space=ss,
search_objectives=search_objectives,
output_dir=self.search_args.output_dir,
num_iters=self.search_args.num_iters,
init_num_models=self.search_args.init_num_models,
num_random_mix=self.search_args.num_random_mix,
max_unseen_population=self.search_args.max_unseen_population,
mutations_per_parent=self.search_args.mutations_per_parent,
num_crossovers=self.search_args.num_crossovers,
seed=self.search_args.seed,
save_pareto_model_weights=False,
)
search_results = algo.search()
results_df = search_results.get_search_state_df()
ids = results_df.archid.values.tolist()
if len(set(ids)) > len(ids):
print("Duplicated models detected in nas results. This is not supposed to happen.")
assert False
configs = []
for archid in ids:
cfg = ss.config_all[archid]
configs.append(cfg)
config_df = pd.DataFrame({"archid": ids, "config": configs})
config_df = results_df.merge(config_df)
output_csv_name = "-".join(["search-results", datetime.now().strftime("%Y%m%d-%H%M%S"), ".csv"])
output_csv_path = os.path.join(self.search_args.output_dir, output_csv_name)
config_df.to_csv(output_csv_path)
return
def _main() -> None:
search = SearchFaceLandmarkModels()
search.search()
if __name__ == "__main__":
_main()
|
archai/tasks/facial_landmark_detection/search.py/0
|
{
"file_path": "archai/tasks/facial_landmark_detection/search.py",
"repo_id": "archai",
"token_count": 2406
}
| 354 |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import torch
from archai.datasets.cv.transforms.lighting import Lighting
def test_lighting_transform():
lighting_transform = Lighting(
std=0.1,
eigval=[0.2126, 0.7152, 0.0722],
eigvec=[[-0.5675, 0.7192, 0.4009], [-0.5808, -0.0045, -0.8140], [-0.5836, -0.6948, 0.4203]],
)
# Asser that it produces a different tensor
img = torch.zeros((3, 256, 256), dtype=torch.float32)
t_img = lighting_transform(img)
assert not torch.allclose(img, t_img, rtol=1e-3, atol=1e-3)
|
archai/tests/datasets/cv/transforms/test_lighting.py/0
|
{
"file_path": "archai/tests/datasets/cv/transforms/test_lighting.py",
"repo_id": "archai",
"token_count": 257
}
| 355 |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import torch
from archai.discrete_search.api.archai_model import ArchaiModel
def test_archai_model():
model = torch.nn.Linear(10, 1)
archid = "test_archid"
metadata = {"key": "value"}
# Assert that attributes are set correctly
archai_model = ArchaiModel(model, archid, metadata)
assert archai_model.arch == model
assert archai_model.archid == archid
assert archai_model.metadata == metadata
assert (
str(archai_model)
== "ArchaiModel(\n\tarchid=test_archid, \n\tmetadata={'key': 'value'}, \n\tarch=Linear(in_features=10, out_features=1, bias=True)\n)"
)
|
archai/tests/discrete_search/api/test_archai_model.py/0
|
{
"file_path": "archai/tests/discrete_search/api/test_archai_model.py",
"repo_id": "archai",
"token_count": 258
}
| 356 |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
from archai.discrete_search.search_spaces.nlp.transformer_flex.models.configuration_mem_transformer import (
MemTransformerConfig,
)
def test_mem_transformer_config():
# Assert that the config has the correct values
config = MemTransformerConfig()
assert config.model_type == "mem-transformer"
assert not config.primer_conv
assert not config.primer_square
assert not config.fp16
assert not config.use_cache
|
archai/tests/discrete_search/search_spaces/nlp/transformer_flex/models/test_configuration_mem_transformer.py/0
|
{
"file_path": "archai/tests/discrete_search/search_spaces/nlp/transformer_flex/models/test_configuration_mem_transformer.py",
"repo_id": "archai",
"token_count": 162
}
| 357 |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import pytest
import torch
from transformers import GPT2Config, GPT2LMHeadModel
from archai.quantization.mixed_qat import MixedQAT
@pytest.fixture
def base_model():
return GPT2LMHeadModel(config=GPT2Config(n_layer=1, resid_pdrop=0.0, embd_pdrop=0.0, attn_pdrop=0.0))
def test_mixed_qat_init(base_model):
# Assert that the `qat_weight` parameter is checked and a ValueError is raised
# if it is not between 0 and 1
with pytest.raises(ValueError):
MixedQAT(base_model, qat_weight=-0.1)
with pytest.raises(ValueError):
MixedQAT(base_model, qat_weight=1.1)
# Assert that the `model` and `qat_model` attributes are correctly initialized
mixed_qat = MixedQAT(base_model)
assert mixed_qat.model is base_model
assert mixed_qat.qat_model is not base_model
# Assert that the parameters of the `model` and `qat_model` are correctly shared
for param, qat_param in zip(base_model.parameters(), mixed_qat.qat_model.parameters()):
assert qat_param is param
def test_mixed_qat_forward(base_model):
mixed_qat = MixedQAT(base_model)
x = torch.zeros((1, 192), dtype=torch.long)
# Assert that the `qat_outputs` are returned when model is not in training mode
mixed_qat.eval()
qat_outputs = mixed_qat.qat_model(input_ids=x, labels=x)
assert qat_outputs.loss == mixed_qat(input_ids=x, labels=x)[0]
# Assert that the linear combination of losses is returned when model is in training mode
mixed_qat.train()
outputs = mixed_qat.model(input_ids=x, labels=x)
qat_outputs = mixed_qat.qat_model(input_ids=x, labels=x)
assert (
outputs.loss * mixed_qat.regular_weight + qat_outputs.loss * mixed_qat.qat_weight
== mixed_qat(input_ids=x, labels=x)[0]
)
|
archai/tests/quantization/test_mixed_qat.py/0
|
{
"file_path": "archai/tests/quantization/test_mixed_qat.py",
"repo_id": "archai",
"token_count": 721
}
| 358 |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
from archai.trainers.nlp.hf_training_args import DistillerTrainingArguments
def test_distiller_training_arguments():
# Assert that the default values for alpha and temperature are correct
args = DistillerTrainingArguments("tmp")
assert args.alpha == 0.5
assert args.temperature == 1.0
# Assert that the custom values for alpha and temperature are correct
args = DistillerTrainingArguments("tmp", alpha=0.75, temperature=1.25)
assert args.alpha == 0.75
assert args.temperature == 1.25
|
archai/tests/trainers/nlp/test_hf_training_args.py/0
|
{
"file_path": "archai/tests/trainers/nlp/test_hf_training_args.py",
"repo_id": "archai",
"token_count": 178
}
| 359 |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
# Generated file, DO NOT EDIT
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------------------------
from msrest import Serializer, Deserializer
from ...client import Client
from ...v7_0.nuget import models
class NuGetClient(Client):
"""NuGet
:param str base_url: Service URL
:param Authentication creds: Authenticated credentials.
"""
def __init__(self, base_url=None, creds=None):
super(NuGetClient, self).__init__(base_url, creds)
client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
self._serialize = Serializer(client_models)
self._deserialize = Deserializer(client_models)
resource_area_identifier = 'b3be7473-68ea-4a81-bfc7-9530baaa19ad'
def get_upstreaming_behavior(self, feed_id, package_name, project=None):
"""GetUpstreamingBehavior.
Get the upstreaming behavior of a package within the context of a feed
:param str feed_id: The name or id of the feed
:param str package_name: The name of the package
:param str project: Project ID or project name
:rtype: :class:`<UpstreamingBehavior> <azure.devops.v7_0.nuget.models.UpstreamingBehavior>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if feed_id is not None:
route_values['feedId'] = self._serialize.url('feed_id', feed_id, 'str')
if package_name is not None:
route_values['packageName'] = self._serialize.url('package_name', package_name, 'str')
response = self._send(http_method='GET',
location_id='b41eec47-6472-4efa-bcd5-a2c5607b66ec',
version='7.0',
route_values=route_values)
return self._deserialize('UpstreamingBehavior', response)
def set_upstreaming_behavior(self, feed_id, package_name, behavior, project=None):
"""SetUpstreamingBehavior.
Set the upstreaming behavior of a package within the context of a feed
:param str feed_id: The name or id of the feed
:param str package_name: The name of the package
:param :class:`<UpstreamingBehavior> <azure.devops.v7_0.nuget.models.UpstreamingBehavior>` behavior: The behavior to apply to the package within the scope of the feed
:param str project: Project ID or project name
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if feed_id is not None:
route_values['feedId'] = self._serialize.url('feed_id', feed_id, 'str')
if package_name is not None:
route_values['packageName'] = self._serialize.url('package_name', package_name, 'str')
content = self._serialize.body(behavior, 'UpstreamingBehavior')
self._send(http_method='PATCH',
location_id='b41eec47-6472-4efa-bcd5-a2c5607b66ec',
version='7.0',
route_values=route_values,
content=content)
def delete_package_version(self, feed_id, package_name, package_version, project=None):
"""DeletePackageVersion.
Send a package version from the feed to its paired recycle bin.
:param str feed_id: Name or ID of the feed.
:param str package_name: Name of the package to delete.
:param str package_version: Version of the package to delete.
:param str project: Project ID or project name
:rtype: :class:`<Package> <azure.devops.v7_0.nuget.models.Package>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if feed_id is not None:
route_values['feedId'] = self._serialize.url('feed_id', feed_id, 'str')
if package_name is not None:
route_values['packageName'] = self._serialize.url('package_name', package_name, 'str')
if package_version is not None:
route_values['packageVersion'] = self._serialize.url('package_version', package_version, 'str')
response = self._send(http_method='DELETE',
location_id='36c9353b-e250-4c57-b040-513c186c3905',
version='7.0',
route_values=route_values)
return self._deserialize('Package', response)
def get_package_version(self, feed_id, package_name, package_version, project=None, show_deleted=None):
"""GetPackageVersion.
Get information about a package version.
:param str feed_id: Name or ID of the feed.
:param str package_name: Name of the package.
:param str package_version: Version of the package.
:param str project: Project ID or project name
:param bool show_deleted: True to include deleted packages in the response.
:rtype: :class:`<Package> <azure.devops.v7_0.nuget.models.Package>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if feed_id is not None:
route_values['feedId'] = self._serialize.url('feed_id', feed_id, 'str')
if package_name is not None:
route_values['packageName'] = self._serialize.url('package_name', package_name, 'str')
if package_version is not None:
route_values['packageVersion'] = self._serialize.url('package_version', package_version, 'str')
query_parameters = {}
if show_deleted is not None:
query_parameters['showDeleted'] = self._serialize.query('show_deleted', show_deleted, 'bool')
response = self._send(http_method='GET',
location_id='36c9353b-e250-4c57-b040-513c186c3905',
version='7.0',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('Package', response)
def update_package_version(self, package_version_details, feed_id, package_name, package_version, project=None):
"""UpdatePackageVersion.
Set mutable state on a package version.
:param :class:`<PackageVersionDetails> <azure.devops.v7_0.nuget.models.PackageVersionDetails>` package_version_details: New state to apply to the referenced package.
:param str feed_id: Name or ID of the feed.
:param str package_name: Name of the package to update.
:param str package_version: Version of the package to update.
:param str project: Project ID or project name
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if feed_id is not None:
route_values['feedId'] = self._serialize.url('feed_id', feed_id, 'str')
if package_name is not None:
route_values['packageName'] = self._serialize.url('package_name', package_name, 'str')
if package_version is not None:
route_values['packageVersion'] = self._serialize.url('package_version', package_version, 'str')
content = self._serialize.body(package_version_details, 'PackageVersionDetails')
self._send(http_method='PATCH',
location_id='36c9353b-e250-4c57-b040-513c186c3905',
version='7.0',
route_values=route_values,
content=content)
|
azure-devops-python-api/azure-devops/azure/devops/released/nuget/nuget_client.py/0
|
{
"file_path": "azure-devops-python-api/azure-devops/azure/devops/released/nuget/nuget_client.py",
"repo_id": "azure-devops-python-api",
"token_count": 3302
}
| 360 |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
# Generated file, DO NOT EDIT
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------------------------
from msrest import Serializer, Deserializer
from ...client import Client
from . import models
class TestResultsClient(Client):
"""TestResults
:param str base_url: Service URL
:param Authentication creds: Authenticated credentials.
"""
def __init__(self, base_url=None, creds=None):
super(TestResultsClient, self).__init__(base_url, creds)
client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
self._serialize = Serializer(client_models)
self._deserialize = Deserializer(client_models)
resource_area_identifier = 'c83eaf52-edf3-4034-ae11-17d38f25404c'
def query_test_results_meta_data(self, test_case_reference_ids, project, details_to_include=None):
"""QueryTestResultsMetaData.
[Preview API] Get list of test Result meta data details for corresponding testcasereferenceId
:param [str] test_case_reference_ids: TestCaseReference Ids of the test Result to be queried, comma separated list of valid ids (limit no. of ids 200).
:param str project: Project ID or project name
:param str details_to_include: Details to include with test results metadata. Default is None. Other values are FlakyIdentifiers.
:rtype: [TestResultMetaData]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
query_parameters = {}
if details_to_include is not None:
query_parameters['detailsToInclude'] = self._serialize.query('details_to_include', details_to_include, 'str')
content = self._serialize.body(test_case_reference_ids, '[str]')
response = self._send(http_method='POST',
location_id='b72ff4c0-4341-4213-ba27-f517cf341c95',
version='7.0-preview.4',
route_values=route_values,
query_parameters=query_parameters,
content=content)
return self._deserialize('[TestResultMetaData]', self._unwrap_collection(response))
def update_test_results_meta_data(self, test_result_meta_data_update_input, project, test_case_reference_id):
"""UpdateTestResultsMetaData.
[Preview API] Update properties of test result meta data
:param :class:`<TestResultMetaDataUpdateInput> <azure.devops.v7_0.test_results.models.TestResultMetaDataUpdateInput>` test_result_meta_data_update_input: TestResultMetaData update input TestResultMetaDataUpdateInput
:param str project: Project ID or project name
:param int test_case_reference_id: TestCaseReference Id of Test Result to be updated.
:rtype: :class:`<TestResultMetaData> <azure.devops.v7_0.test_results.models.TestResultMetaData>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if test_case_reference_id is not None:
route_values['testCaseReferenceId'] = self._serialize.url('test_case_reference_id', test_case_reference_id, 'int')
content = self._serialize.body(test_result_meta_data_update_input, 'TestResultMetaDataUpdateInput')
response = self._send(http_method='PATCH',
location_id='b72ff4c0-4341-4213-ba27-f517cf341c95',
version='7.0-preview.4',
route_values=route_values,
content=content)
return self._deserialize('TestResultMetaData', response)
def get_test_result_logs(self, project, run_id, result_id, type, directory_path=None, file_name_prefix=None, fetch_meta_data=None, top=None, continuation_token=None):
"""GetTestResultLogs.
[Preview API] Get list of test result attachments reference
:param str project: Project ID or project name
:param int run_id: Id of the test run that contains the result
:param int result_id: Id of the test result
:param str type: type of attachments to get
:param str directory_path: directory path of attachments to get
:param str file_name_prefix: file name prefix to filter the list of attachment
:param bool fetch_meta_data: Default is false, set if metadata is needed
:param int top: Numbe of attachments reference to return
:param String continuation_token: Header to pass the continuationToken
:rtype: :class:`<[TestLog]> <azure.devops.v7_0.test_results.models.[TestLog]>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if run_id is not None:
route_values['runId'] = self._serialize.url('run_id', run_id, 'int')
if result_id is not None:
route_values['resultId'] = self._serialize.url('result_id', result_id, 'int')
query_parameters = {}
if type is not None:
query_parameters['type'] = self._serialize.query('type', type, 'str')
if directory_path is not None:
query_parameters['directoryPath'] = self._serialize.query('directory_path', directory_path, 'str')
if file_name_prefix is not None:
query_parameters['fileNamePrefix'] = self._serialize.query('file_name_prefix', file_name_prefix, 'str')
if fetch_meta_data is not None:
query_parameters['fetchMetaData'] = self._serialize.query('fetch_meta_data', fetch_meta_data, 'bool')
if top is not None:
query_parameters['top'] = self._serialize.query('top', top, 'int')
additional_headers = {}
if continuation_token is not None:
additional_headers['x-ms-continuationtoken'] = continuation_token
response = self._send(http_method='GET',
location_id='714caaac-ae1e-4869-8323-9bc0f5120dbf',
version='7.0-preview.1',
route_values=route_values,
query_parameters=query_parameters,
additional_headers=additional_headers)
return self._deserialize('[TestLog]', self._unwrap_collection(response))
def get_test_sub_result_logs(self, project, run_id, result_id, sub_result_id, type, directory_path=None, file_name_prefix=None, fetch_meta_data=None, top=None, continuation_token=None):
"""GetTestSubResultLogs.
[Preview API] Get list of test subresult attachments reference
:param str project: Project ID or project name
:param int run_id: Id of the test run that contains the results
:param int result_id: Id of the test result that contains subresult
:param int sub_result_id: Id of the test subresult
:param str type: type of the attachments to get
:param str directory_path: directory path of the attachment to get
:param str file_name_prefix: file name prefix to filter the list of attachments
:param bool fetch_meta_data: Default is false, set if metadata is needed
:param int top: Number of attachments reference to return
:param String continuation_token: Header to pass the continuationToken
:rtype: :class:`<[TestLog]> <azure.devops.v7_0.test_results.models.[TestLog]>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if run_id is not None:
route_values['runId'] = self._serialize.url('run_id', run_id, 'int')
if result_id is not None:
route_values['resultId'] = self._serialize.url('result_id', result_id, 'int')
query_parameters = {}
if sub_result_id is not None:
query_parameters['subResultId'] = self._serialize.query('sub_result_id', sub_result_id, 'int')
if type is not None:
query_parameters['type'] = self._serialize.query('type', type, 'str')
if directory_path is not None:
query_parameters['directoryPath'] = self._serialize.query('directory_path', directory_path, 'str')
if file_name_prefix is not None:
query_parameters['fileNamePrefix'] = self._serialize.query('file_name_prefix', file_name_prefix, 'str')
if fetch_meta_data is not None:
query_parameters['fetchMetaData'] = self._serialize.query('fetch_meta_data', fetch_meta_data, 'bool')
if top is not None:
query_parameters['top'] = self._serialize.query('top', top, 'int')
additional_headers = {}
if continuation_token is not None:
additional_headers['x-ms-continuationtoken'] = continuation_token
response = self._send(http_method='GET',
location_id='714caaac-ae1e-4869-8323-9bc0f5120dbf',
version='7.0-preview.1',
route_values=route_values,
query_parameters=query_parameters,
additional_headers=additional_headers)
return self._deserialize('[TestLog]', self._unwrap_collection(response))
def get_test_run_logs(self, project, run_id, type, directory_path=None, file_name_prefix=None, fetch_meta_data=None, top=None, continuation_token=None):
"""GetTestRunLogs.
[Preview API] Get list of test run attachments reference
:param str project: Project ID or project name
:param int run_id: Id of the test run
:param str type: type of the attachments to get
:param str directory_path: directory path for which attachments are needed
:param str file_name_prefix: file name prefix to filter the list of attachment
:param bool fetch_meta_data: Default is false, set if metadata is needed
:param int top: Number of attachments reference to return
:param String continuation_token: Header to pass the continuationToken
:rtype: :class:`<[TestLog]> <azure.devops.v7_0.test_results.models.[TestLog]>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if run_id is not None:
route_values['runId'] = self._serialize.url('run_id', run_id, 'int')
query_parameters = {}
if type is not None:
query_parameters['type'] = self._serialize.query('type', type, 'str')
if directory_path is not None:
query_parameters['directoryPath'] = self._serialize.query('directory_path', directory_path, 'str')
if file_name_prefix is not None:
query_parameters['fileNamePrefix'] = self._serialize.query('file_name_prefix', file_name_prefix, 'str')
if fetch_meta_data is not None:
query_parameters['fetchMetaData'] = self._serialize.query('fetch_meta_data', fetch_meta_data, 'bool')
if top is not None:
query_parameters['top'] = self._serialize.query('top', top, 'int')
additional_headers = {}
if continuation_token is not None:
additional_headers['x-ms-continuationtoken'] = continuation_token
response = self._send(http_method='GET',
location_id='5b47b946-e875-4c9a-acdc-2a20996caebe',
version='7.0-preview.1',
route_values=route_values,
query_parameters=query_parameters,
additional_headers=additional_headers)
return self._deserialize('[TestLog]', self._unwrap_collection(response))
def get_test_log_store_endpoint_details_for_result_log(self, project, run_id, result_id, type, file_path):
"""GetTestLogStoreEndpointDetailsForResultLog.
[Preview API] Get SAS Uri of a test results attachment
:param str project: Project ID or project name
:param int run_id: Id of the test run that contains result
:param int result_id: Id of the test result whose files need to be downloaded
:param str type: type of the file
:param str file_path: filePath for which sas uri is needed
:rtype: :class:`<TestLogStoreEndpointDetails> <azure.devops.v7_0.test_results.models.TestLogStoreEndpointDetails>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if run_id is not None:
route_values['runId'] = self._serialize.url('run_id', run_id, 'int')
if result_id is not None:
route_values['resultId'] = self._serialize.url('result_id', result_id, 'int')
query_parameters = {}
if type is not None:
query_parameters['type'] = self._serialize.query('type', type, 'str')
if file_path is not None:
query_parameters['filePath'] = self._serialize.query('file_path', file_path, 'str')
response = self._send(http_method='GET',
location_id='da630b37-1236-45b5-945e-1d7bdb673850',
version='7.0-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('TestLogStoreEndpointDetails', response)
def get_test_log_store_endpoint_details_for_sub_result_log(self, project, run_id, result_id, sub_result_id, type, file_path):
"""GetTestLogStoreEndpointDetailsForSubResultLog.
[Preview API] Get SAS Uri of a test subresults attachment
:param str project: Project ID or project name
:param int run_id: Id of the test run that contains result
:param int result_id: Id of the test result that contains subresult
:param int sub_result_id: Id of the test subresult whose file sas uri is needed
:param str type: type of the file
:param str file_path: filePath for which sas uri is needed
:rtype: :class:`<TestLogStoreEndpointDetails> <azure.devops.v7_0.test_results.models.TestLogStoreEndpointDetails>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if run_id is not None:
route_values['runId'] = self._serialize.url('run_id', run_id, 'int')
if result_id is not None:
route_values['resultId'] = self._serialize.url('result_id', result_id, 'int')
query_parameters = {}
if sub_result_id is not None:
query_parameters['subResultId'] = self._serialize.query('sub_result_id', sub_result_id, 'int')
if type is not None:
query_parameters['type'] = self._serialize.query('type', type, 'str')
if file_path is not None:
query_parameters['filePath'] = self._serialize.query('file_path', file_path, 'str')
response = self._send(http_method='GET',
location_id='da630b37-1236-45b5-945e-1d7bdb673850',
version='7.0-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('TestLogStoreEndpointDetails', response)
def test_log_store_endpoint_details_for_result(self, project, run_id, result_id, sub_result_id, file_path, type):
"""TestLogStoreEndpointDetailsForResult.
[Preview API] Create empty file for a result and Get Sas uri for the file
:param str project: Project ID or project name
:param int run_id: Id of the test run that contains the result
:param int result_id: Id of the test results that contains sub result
:param int sub_result_id: Id of the test sub result whose file sas uri is needed
:param str file_path: file path inside the sub result for which sas uri is needed
:param str type: Type of the file for download
:rtype: :class:`<TestLogStoreEndpointDetails> <azure.devops.v7_0.test_results.models.TestLogStoreEndpointDetails>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if run_id is not None:
route_values['runId'] = self._serialize.url('run_id', run_id, 'int')
if result_id is not None:
route_values['resultId'] = self._serialize.url('result_id', result_id, 'int')
query_parameters = {}
if sub_result_id is not None:
query_parameters['subResultId'] = self._serialize.query('sub_result_id', sub_result_id, 'int')
if file_path is not None:
query_parameters['filePath'] = self._serialize.query('file_path', file_path, 'str')
if type is not None:
query_parameters['type'] = self._serialize.query('type', type, 'str')
response = self._send(http_method='POST',
location_id='da630b37-1236-45b5-945e-1d7bdb673850',
version='7.0-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('TestLogStoreEndpointDetails', response)
def get_test_log_store_endpoint_details_for_run_log(self, project, run_id, type, file_path):
"""GetTestLogStoreEndpointDetailsForRunLog.
[Preview API] Get SAS Uri of a test run attachment
:param str project: Project ID or project name
:param int run_id: Id of the test run whose file has to be downloaded
:param str type: type of the file
:param str file_path: filePath for which sas uri is needed
:rtype: :class:`<TestLogStoreEndpointDetails> <azure.devops.v7_0.test_results.models.TestLogStoreEndpointDetails>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if run_id is not None:
route_values['runId'] = self._serialize.url('run_id', run_id, 'int')
query_parameters = {}
if type is not None:
query_parameters['type'] = self._serialize.query('type', type, 'str')
if file_path is not None:
query_parameters['filePath'] = self._serialize.query('file_path', file_path, 'str')
response = self._send(http_method='GET',
location_id='67eb3f92-6c97-4fd9-8b63-6cbdc7e526ea',
version='7.0-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('TestLogStoreEndpointDetails', response)
def test_log_store_endpoint_details_for_run(self, project, run_id, test_log_store_operation_type, file_path=None, type=None):
"""TestLogStoreEndpointDetailsForRun.
[Preview API] Create empty file for a run and Get Sas uri for the file
:param str project: Project ID or project name
:param int run_id: Id of the run to get endpoint details
:param str test_log_store_operation_type: Type of operation to perform using sas uri
:param str file_path: file path to create an empty file
:param str type: Default is GeneralAttachment, type of empty file to be created
:rtype: :class:`<TestLogStoreEndpointDetails> <azure.devops.v7_0.test_results.models.TestLogStoreEndpointDetails>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if run_id is not None:
route_values['runId'] = self._serialize.url('run_id', run_id, 'int')
query_parameters = {}
if test_log_store_operation_type is not None:
query_parameters['testLogStoreOperationType'] = self._serialize.query('test_log_store_operation_type', test_log_store_operation_type, 'str')
if file_path is not None:
query_parameters['filePath'] = self._serialize.query('file_path', file_path, 'str')
if type is not None:
query_parameters['type'] = self._serialize.query('type', type, 'str')
response = self._send(http_method='POST',
location_id='67eb3f92-6c97-4fd9-8b63-6cbdc7e526ea',
version='7.0-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('TestLogStoreEndpointDetails', response)
|
azure-devops-python-api/azure-devops/azure/devops/v7_0/test_results/test_results_client.py/0
|
{
"file_path": "azure-devops-python-api/azure-devops/azure/devops/v7_0/test_results/test_results_client.py",
"repo_id": "azure-devops-python-api",
"token_count": 8925
}
| 361 |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
# Generated file, DO NOT EDIT
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------------------------
from msrest import Serializer, Deserializer
from ...client import Client
from . import models
class FeatureAvailabilityClient(Client):
"""FeatureAvailability
:param str base_url: Service URL
:param Authentication creds: Authenticated credentials.
"""
def __init__(self, base_url=None, creds=None):
super(FeatureAvailabilityClient, self).__init__(base_url, creds)
client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
self._serialize = Serializer(client_models)
self._deserialize = Deserializer(client_models)
resource_area_identifier = None
def get_all_feature_flags(self, user_email=None):
"""GetAllFeatureFlags.
[Preview API] Retrieve a listing of all feature flags and their current states for a user
:param str user_email: The email of the user to check
:rtype: [FeatureFlag]
"""
query_parameters = {}
if user_email is not None:
query_parameters['userEmail'] = self._serialize.query('user_email', user_email, 'str')
response = self._send(http_method='GET',
location_id='3e2b80f8-9e6f-441e-8393-005610692d9c',
version='7.1-preview.1',
query_parameters=query_parameters)
return self._deserialize('[FeatureFlag]', self._unwrap_collection(response))
def get_feature_flag_by_name(self, name, check_feature_exists=None):
"""GetFeatureFlagByName.
[Preview API] Retrieve information on a single feature flag and its current states
:param str name: The name of the feature to retrieve
:param bool check_feature_exists: Check if feature exists
:rtype: :class:`<FeatureFlag> <azure.devops.v7_1.feature_availability.models.FeatureFlag>`
"""
route_values = {}
if name is not None:
route_values['name'] = self._serialize.url('name', name, 'str')
query_parameters = {}
if check_feature_exists is not None:
query_parameters['checkFeatureExists'] = self._serialize.query('check_feature_exists', check_feature_exists, 'bool')
response = self._send(http_method='GET',
location_id='3e2b80f8-9e6f-441e-8393-005610692d9c',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('FeatureFlag', response)
def get_feature_flag_by_name_and_user_email(self, name, user_email, check_feature_exists=None):
"""GetFeatureFlagByNameAndUserEmail.
[Preview API] Retrieve information on a single feature flag and its current states for a user
:param str name: The name of the feature to retrieve
:param str user_email: The email of the user to check
:param bool check_feature_exists: Check if feature exists
:rtype: :class:`<FeatureFlag> <azure.devops.v7_1.feature_availability.models.FeatureFlag>`
"""
route_values = {}
if name is not None:
route_values['name'] = self._serialize.url('name', name, 'str')
query_parameters = {}
if user_email is not None:
query_parameters['userEmail'] = self._serialize.query('user_email', user_email, 'str')
if check_feature_exists is not None:
query_parameters['checkFeatureExists'] = self._serialize.query('check_feature_exists', check_feature_exists, 'bool')
response = self._send(http_method='GET',
location_id='3e2b80f8-9e6f-441e-8393-005610692d9c',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('FeatureFlag', response)
def get_feature_flag_by_name_and_user_id(self, name, user_id, check_feature_exists=None):
"""GetFeatureFlagByNameAndUserId.
[Preview API] Retrieve information on a single feature flag and its current states for a user
:param str name: The name of the feature to retrieve
:param str user_id: The id of the user to check
:param bool check_feature_exists: Check if feature exists
:rtype: :class:`<FeatureFlag> <azure.devops.v7_1.feature_availability.models.FeatureFlag>`
"""
route_values = {}
if name is not None:
route_values['name'] = self._serialize.url('name', name, 'str')
query_parameters = {}
if user_id is not None:
query_parameters['userId'] = self._serialize.query('user_id', user_id, 'str')
if check_feature_exists is not None:
query_parameters['checkFeatureExists'] = self._serialize.query('check_feature_exists', check_feature_exists, 'bool')
response = self._send(http_method='GET',
location_id='3e2b80f8-9e6f-441e-8393-005610692d9c',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('FeatureFlag', response)
def update_feature_flag(self, state, name, user_email=None, check_feature_exists=None, set_at_application_level_also=None):
"""UpdateFeatureFlag.
[Preview API] Change the state of an individual feature flag for a name
:param :class:`<FeatureFlagPatch> <azure.devops.v7_1.feature_availability.models.FeatureFlagPatch>` state: State that should be set
:param str name: The name of the feature to change
:param str user_email:
:param bool check_feature_exists: Checks if the feature exists before setting the state
:param bool set_at_application_level_also:
:rtype: :class:`<FeatureFlag> <azure.devops.v7_1.feature_availability.models.FeatureFlag>`
"""
route_values = {}
if name is not None:
route_values['name'] = self._serialize.url('name', name, 'str')
query_parameters = {}
if user_email is not None:
query_parameters['userEmail'] = self._serialize.query('user_email', user_email, 'str')
if check_feature_exists is not None:
query_parameters['checkFeatureExists'] = self._serialize.query('check_feature_exists', check_feature_exists, 'bool')
if set_at_application_level_also is not None:
query_parameters['setAtApplicationLevelAlso'] = self._serialize.query('set_at_application_level_also', set_at_application_level_also, 'bool')
content = self._serialize.body(state, 'FeatureFlagPatch')
response = self._send(http_method='PATCH',
location_id='3e2b80f8-9e6f-441e-8393-005610692d9c',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters,
content=content)
return self._deserialize('FeatureFlag', response)
|
azure-devops-python-api/azure-devops/azure/devops/v7_1/feature_availability/feature_availability_client.py/0
|
{
"file_path": "azure-devops-python-api/azure-devops/azure/devops/v7_1/feature_availability/feature_availability_client.py",
"repo_id": "azure-devops-python-api",
"token_count": 3217
}
| 362 |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
# Generated file, DO NOT EDIT
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------------------------
from msrest import Serializer, Deserializer
from ...client import Client
from . import models
class GitClientBase(Client):
"""Git
:param str base_url: Service URL
:param Authentication creds: Authenticated credentials.
"""
def __init__(self, base_url=None, creds=None):
super(GitClientBase, self).__init__(base_url, creds)
client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
self._serialize = Serializer(client_models)
self._deserialize = Deserializer(client_models)
resource_area_identifier = '4e080c62-fa21-4fbc-8fef-2a10a2b38049'
def get_permission(self, project_name=None, repository_id=None, permission=None):
"""GetPermission.
[Preview API] GET Advanced Security Permission status.
:param str project_name:
:param str repository_id: Repository user is trying to access
:param str permission: Permission being requestd, must be "viewAlert" "dismissAlert" or "manage"
:rtype: bool
"""
query_parameters = {}
if project_name is not None:
query_parameters['$projectName'] = self._serialize.query('project_name', project_name, 'str')
if repository_id is not None:
query_parameters['$repositoryId'] = self._serialize.query('repository_id', repository_id, 'str')
if permission is not None:
query_parameters['$permission'] = self._serialize.query('permission', permission, 'str')
response = self._send(http_method='GET',
location_id='61b21a05-a60f-4910-a733-ba5347c2142d',
version='7.1-preview.1',
query_parameters=query_parameters)
return self._deserialize('bool', response)
def create_annotated_tag(self, tag_object, project, repository_id):
"""CreateAnnotatedTag.
[Preview API] Create an annotated tag.
:param :class:`<GitAnnotatedTag> <azure.devops.v7_1.git.models.GitAnnotatedTag>` tag_object: Object containing details of tag to be created.
:param str project: Project ID or project name
:param str repository_id: ID or name of the repository.
:rtype: :class:`<GitAnnotatedTag> <azure.devops.v7_1.git.models.GitAnnotatedTag>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
content = self._serialize.body(tag_object, 'GitAnnotatedTag')
response = self._send(http_method='POST',
location_id='5e8a8081-3851-4626-b677-9891cc04102e',
version='7.1-preview.1',
route_values=route_values,
content=content)
return self._deserialize('GitAnnotatedTag', response)
def get_annotated_tag(self, project, repository_id, object_id):
"""GetAnnotatedTag.
[Preview API] Get an annotated tag.
:param str project: Project ID or project name
:param str repository_id: ID or name of the repository.
:param str object_id: ObjectId (Sha1Id) of tag to get.
:rtype: :class:`<GitAnnotatedTag> <azure.devops.v7_1.git.models.GitAnnotatedTag>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if object_id is not None:
route_values['objectId'] = self._serialize.url('object_id', object_id, 'str')
response = self._send(http_method='GET',
location_id='5e8a8081-3851-4626-b677-9891cc04102e',
version='7.1-preview.1',
route_values=route_values)
return self._deserialize('GitAnnotatedTag', response)
def get_blob(self, repository_id, sha1, project=None, download=None, file_name=None, resolve_lfs=None):
"""GetBlob.
[Preview API] Get a single blob.
:param str repository_id: The name or ID of the repository.
:param str sha1: SHA1 hash of the file. You can get the SHA1 of a file using the "Git/Items/Get Item" endpoint.
:param str project: Project ID or project name
:param bool download: If true, prompt for a download rather than rendering in a browser. Note: this value defaults to true if $format is zip
:param str file_name: Provide a fileName to use for a download.
:param bool resolve_lfs: If true, try to resolve a blob to its LFS contents, if it's an LFS pointer file. Only compatible with octet-stream Accept headers or $format types
:rtype: :class:`<GitBlobRef> <azure.devops.v7_1.git.models.GitBlobRef>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if sha1 is not None:
route_values['sha1'] = self._serialize.url('sha1', sha1, 'str')
query_parameters = {}
if download is not None:
query_parameters['download'] = self._serialize.query('download', download, 'bool')
if file_name is not None:
query_parameters['fileName'] = self._serialize.query('file_name', file_name, 'str')
if resolve_lfs is not None:
query_parameters['resolveLfs'] = self._serialize.query('resolve_lfs', resolve_lfs, 'bool')
response = self._send(http_method='GET',
location_id='7b28e929-2c99-405d-9c5c-6167a06e6816',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('GitBlobRef', response)
def get_blob_content(self, repository_id, sha1, project=None, download=None, file_name=None, resolve_lfs=None, **kwargs):
"""GetBlobContent.
[Preview API] Get a single blob.
:param str repository_id: The name or ID of the repository.
:param str sha1: SHA1 hash of the file. You can get the SHA1 of a file using the "Git/Items/Get Item" endpoint.
:param str project: Project ID or project name
:param bool download: If true, prompt for a download rather than rendering in a browser. Note: this value defaults to true if $format is zip
:param str file_name: Provide a fileName to use for a download.
:param bool resolve_lfs: If true, try to resolve a blob to its LFS contents, if it's an LFS pointer file. Only compatible with octet-stream Accept headers or $format types
:rtype: object
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if sha1 is not None:
route_values['sha1'] = self._serialize.url('sha1', sha1, 'str')
query_parameters = {}
if download is not None:
query_parameters['download'] = self._serialize.query('download', download, 'bool')
if file_name is not None:
query_parameters['fileName'] = self._serialize.query('file_name', file_name, 'str')
if resolve_lfs is not None:
query_parameters['resolveLfs'] = self._serialize.query('resolve_lfs', resolve_lfs, 'bool')
response = self._send(http_method='GET',
location_id='7b28e929-2c99-405d-9c5c-6167a06e6816',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters,
accept_media_type='application/octet-stream')
if "callback" in kwargs:
callback = kwargs["callback"]
else:
callback = None
return self._client.stream_download(response, callback=callback)
def get_blobs_zip(self, blob_ids, repository_id, project=None, filename=None, **kwargs):
"""GetBlobsZip.
[Preview API] Gets one or more blobs in a zip file download.
:param [str] blob_ids: Blob IDs (SHA1 hashes) to be returned in the zip file.
:param str repository_id: The name or ID of the repository.
:param str project: Project ID or project name
:param str filename:
:rtype: object
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
query_parameters = {}
if filename is not None:
query_parameters['filename'] = self._serialize.query('filename', filename, 'str')
content = self._serialize.body(blob_ids, '[str]')
response = self._send(http_method='POST',
location_id='7b28e929-2c99-405d-9c5c-6167a06e6816',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters,
content=content,
accept_media_type='application/zip')
if "callback" in kwargs:
callback = kwargs["callback"]
else:
callback = None
return self._client.stream_download(response, callback=callback)
def get_blob_zip(self, repository_id, sha1, project=None, download=None, file_name=None, resolve_lfs=None, **kwargs):
"""GetBlobZip.
[Preview API] Get a single blob.
:param str repository_id: The name or ID of the repository.
:param str sha1: SHA1 hash of the file. You can get the SHA1 of a file using the "Git/Items/Get Item" endpoint.
:param str project: Project ID or project name
:param bool download: If true, prompt for a download rather than rendering in a browser. Note: this value defaults to true if $format is zip
:param str file_name: Provide a fileName to use for a download.
:param bool resolve_lfs: If true, try to resolve a blob to its LFS contents, if it's an LFS pointer file. Only compatible with octet-stream Accept headers or $format types
:rtype: object
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if sha1 is not None:
route_values['sha1'] = self._serialize.url('sha1', sha1, 'str')
query_parameters = {}
if download is not None:
query_parameters['download'] = self._serialize.query('download', download, 'bool')
if file_name is not None:
query_parameters['fileName'] = self._serialize.query('file_name', file_name, 'str')
if resolve_lfs is not None:
query_parameters['resolveLfs'] = self._serialize.query('resolve_lfs', resolve_lfs, 'bool')
response = self._send(http_method='GET',
location_id='7b28e929-2c99-405d-9c5c-6167a06e6816',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters,
accept_media_type='application/zip')
if "callback" in kwargs:
callback = kwargs["callback"]
else:
callback = None
return self._client.stream_download(response, callback=callback)
def get_branch(self, repository_id, name, project=None, base_version_descriptor=None):
"""GetBranch.
[Preview API] Retrieve statistics about a single branch.
:param str repository_id: The name or ID of the repository.
:param str name: Name of the branch.
:param str project: Project ID or project name
:param :class:`<GitVersionDescriptor> <azure.devops.v7_1.git.models.GitVersionDescriptor>` base_version_descriptor: Identifies the commit or branch to use as the base.
:rtype: :class:`<GitBranchStats> <azure.devops.v7_1.git.models.GitBranchStats>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
query_parameters = {}
if name is not None:
query_parameters['name'] = self._serialize.query('name', name, 'str')
if base_version_descriptor is not None:
if base_version_descriptor.version_type is not None:
query_parameters['baseVersionDescriptor.versionType'] = base_version_descriptor.version_type
if base_version_descriptor.version is not None:
query_parameters['baseVersionDescriptor.version'] = base_version_descriptor.version
if base_version_descriptor.version_options is not None:
query_parameters['baseVersionDescriptor.versionOptions'] = base_version_descriptor.version_options
response = self._send(http_method='GET',
location_id='d5b216de-d8d5-4d32-ae76-51df755b16d3',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('GitBranchStats', response)
def get_branches(self, repository_id, project=None, base_version_descriptor=None):
"""GetBranches.
[Preview API] Retrieve statistics about all branches within a repository.
:param str repository_id: The name or ID of the repository.
:param str project: Project ID or project name
:param :class:`<GitVersionDescriptor> <azure.devops.v7_1.git.models.GitVersionDescriptor>` base_version_descriptor: Identifies the commit or branch to use as the base.
:rtype: [GitBranchStats]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
query_parameters = {}
if base_version_descriptor is not None:
if base_version_descriptor.version_type is not None:
query_parameters['baseVersionDescriptor.versionType'] = base_version_descriptor.version_type
if base_version_descriptor.version is not None:
query_parameters['baseVersionDescriptor.version'] = base_version_descriptor.version
if base_version_descriptor.version_options is not None:
query_parameters['baseVersionDescriptor.versionOptions'] = base_version_descriptor.version_options
response = self._send(http_method='GET',
location_id='d5b216de-d8d5-4d32-ae76-51df755b16d3',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('[GitBranchStats]', self._unwrap_collection(response))
def get_commit_diffs(self, repository_id, project=None, diff_common_commit=None, top=None, skip=None, base_version_descriptor=None, target_version_descriptor=None):
"""GetCommitDiffs.
[Preview API] Find the closest common commit (the merge base) between base and target commits, and get the diff between either the base and target commits or common and target commits.
:param str repository_id: The name or ID of the repository.
:param str project: Project ID or project name
:param bool diff_common_commit: If true, diff between common and target commits. If false, diff between base and target commits.
:param int top: Maximum number of changes to return. Defaults to 100.
:param int skip: Number of changes to skip
:param :class:`<GitBaseVersionDescriptor> <azure.devops.v7_1.git.models.GitBaseVersionDescriptor>` base_version_descriptor: Descriptor for base commit.
:param :class:`<GitTargetVersionDescriptor> <azure.devops.v7_1.git.models.GitTargetVersionDescriptor>` target_version_descriptor: Descriptor for target commit.
:rtype: :class:`<GitCommitDiffs> <azure.devops.v7_1.git.models.GitCommitDiffs>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
query_parameters = {}
if diff_common_commit is not None:
query_parameters['diffCommonCommit'] = self._serialize.query('diff_common_commit', diff_common_commit, 'bool')
if top is not None:
query_parameters['$top'] = self._serialize.query('top', top, 'int')
if skip is not None:
query_parameters['$skip'] = self._serialize.query('skip', skip, 'int')
if base_version_descriptor is not None:
if base_version_descriptor.base_version_type is not None:
query_parameters['baseVersionType'] = base_version_descriptor.base_version_type
if base_version_descriptor.base_version is not None:
query_parameters['baseVersion'] = base_version_descriptor.base_version
if base_version_descriptor.base_version_options is not None:
query_parameters['baseVersionOptions'] = base_version_descriptor.base_version_options
if target_version_descriptor is not None:
if target_version_descriptor.target_version_type is not None:
query_parameters['targetVersionType'] = target_version_descriptor.target_version_type
if target_version_descriptor.target_version is not None:
query_parameters['targetVersion'] = target_version_descriptor.target_version
if target_version_descriptor.target_version_options is not None:
query_parameters['targetVersionOptions'] = target_version_descriptor.target_version_options
response = self._send(http_method='GET',
location_id='615588d5-c0c7-4b88-88f8-e625306446e8',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('GitCommitDiffs', response)
def get_commit(self, commit_id, repository_id, project=None, change_count=None):
"""GetCommit.
[Preview API] Retrieve a particular commit.
:param str commit_id: The id of the commit.
:param str repository_id: The id or friendly name of the repository. To use the friendly name, projectId must also be specified.
:param str project: Project ID or project name
:param int change_count: The number of changes to include in the result.
:rtype: :class:`<GitCommit> <azure.devops.v7_1.git.models.GitCommit>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if commit_id is not None:
route_values['commitId'] = self._serialize.url('commit_id', commit_id, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
query_parameters = {}
if change_count is not None:
query_parameters['changeCount'] = self._serialize.query('change_count', change_count, 'int')
response = self._send(http_method='GET',
location_id='c2570c3b-5b3f-41b8-98bf-5407bfde8d58',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('GitCommit', response)
def get_commits(self, repository_id, search_criteria, project=None, skip=None, top=None):
"""GetCommits.
[Preview API] Retrieve git commits for a project
:param str repository_id: The id or friendly name of the repository. To use the friendly name, projectId must also be specified.
:param :class:`<GitQueryCommitsCriteria> <azure.devops.v7_1.git.models.GitQueryCommitsCriteria>` search_criteria:
:param str project: Project ID or project name
:param int skip:
:param int top:
:rtype: [GitCommitRef]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
query_parameters = {}
if search_criteria is not None:
if search_criteria.ids is not None:
query_parameters['searchCriteria.ids'] = search_criteria.ids
if search_criteria.from_date is not None:
query_parameters['searchCriteria.fromDate'] = search_criteria.from_date
if search_criteria.to_date is not None:
query_parameters['searchCriteria.toDate'] = search_criteria.to_date
if search_criteria.item_version is not None:
if search_criteria.item_version.version_type is not None:
query_parameters['searchCriteria.itemVersion.versionType'] = search_criteria.item_version.version_type
if search_criteria.item_version.version is not None:
query_parameters['searchCriteria.itemVersion.version'] = search_criteria.item_version.version
if search_criteria.item_version.version_options is not None:
query_parameters['searchCriteria.itemVersion.versionOptions'] = search_criteria.item_version.version_options
if search_criteria.compare_version is not None:
if search_criteria.compare_version.version_type is not None:
query_parameters['searchCriteria.compareVersion.versionType'] = search_criteria.compare_version.version_type
if search_criteria.compare_version.version is not None:
query_parameters['searchCriteria.compareVersion.version'] = search_criteria.compare_version.version
if search_criteria.compare_version.version_options is not None:
query_parameters['searchCriteria.compareVersion.versionOptions'] = search_criteria.compare_version.version_options
if search_criteria.from_commit_id is not None:
query_parameters['searchCriteria.fromCommitId'] = search_criteria.from_commit_id
if search_criteria.to_commit_id is not None:
query_parameters['searchCriteria.toCommitId'] = search_criteria.to_commit_id
if search_criteria.user is not None:
query_parameters['searchCriteria.user'] = search_criteria.user
if search_criteria.author is not None:
query_parameters['searchCriteria.author'] = search_criteria.author
if search_criteria.item_path is not None:
query_parameters['searchCriteria.itemPath'] = search_criteria.item_path
if search_criteria.exclude_deletes is not None:
query_parameters['searchCriteria.excludeDeletes'] = search_criteria.exclude_deletes
if search_criteria.skip is not None:
query_parameters['searchCriteria.$skip'] = search_criteria.skip
if search_criteria.top is not None:
query_parameters['searchCriteria.$top'] = search_criteria.top
if search_criteria.include_links is not None:
query_parameters['searchCriteria.includeLinks'] = search_criteria.include_links
if search_criteria.include_work_items is not None:
query_parameters['searchCriteria.includeWorkItems'] = search_criteria.include_work_items
if search_criteria.include_user_image_url is not None:
query_parameters['searchCriteria.includeUserImageUrl'] = search_criteria.include_user_image_url
if search_criteria.include_push_data is not None:
query_parameters['searchCriteria.includePushData'] = search_criteria.include_push_data
if search_criteria.history_mode is not None:
query_parameters['searchCriteria.historyMode'] = search_criteria.history_mode
if search_criteria.show_oldest_commits_first is not None:
query_parameters['searchCriteria.showOldestCommitsFirst'] = search_criteria.show_oldest_commits_first
if skip is not None:
query_parameters['$skip'] = self._serialize.query('skip', skip, 'int')
if top is not None:
query_parameters['$top'] = self._serialize.query('top', top, 'int')
response = self._send(http_method='GET',
location_id='c2570c3b-5b3f-41b8-98bf-5407bfde8d58',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('[GitCommitRef]', self._unwrap_collection(response))
def get_push_commits(self, repository_id, push_id, project=None, top=None, skip=None, include_links=None):
"""GetPushCommits.
[Preview API] Retrieve a list of commits associated with a particular push.
:param str repository_id: The id or friendly name of the repository. To use the friendly name, projectId must also be specified.
:param int push_id: The id of the push.
:param str project: Project ID or project name
:param int top: The maximum number of commits to return ("get the top x commits").
:param int skip: The number of commits to skip.
:param bool include_links: Set to false to avoid including REST Url links for resources. Defaults to true.
:rtype: [GitCommitRef]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
query_parameters = {}
if push_id is not None:
query_parameters['pushId'] = self._serialize.query('push_id', push_id, 'int')
if top is not None:
query_parameters['top'] = self._serialize.query('top', top, 'int')
if skip is not None:
query_parameters['skip'] = self._serialize.query('skip', skip, 'int')
if include_links is not None:
query_parameters['includeLinks'] = self._serialize.query('include_links', include_links, 'bool')
response = self._send(http_method='GET',
location_id='c2570c3b-5b3f-41b8-98bf-5407bfde8d58',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('[GitCommitRef]', self._unwrap_collection(response))
def get_commits_batch(self, search_criteria, repository_id, project=None, skip=None, top=None, include_statuses=None):
"""GetCommitsBatch.
[Preview API] Retrieve git commits for a project matching the search criteria
:param :class:`<GitQueryCommitsCriteria> <azure.devops.v7_1.git.models.GitQueryCommitsCriteria>` search_criteria: Search options
:param str repository_id: The name or ID of the repository.
:param str project: Project ID or project name
:param int skip: Number of commits to skip.
:param int top: Maximum number of commits to return.
:param bool include_statuses: True to include additional commit status information.
:rtype: [GitCommitRef]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
query_parameters = {}
if skip is not None:
query_parameters['$skip'] = self._serialize.query('skip', skip, 'int')
if top is not None:
query_parameters['$top'] = self._serialize.query('top', top, 'int')
if include_statuses is not None:
query_parameters['includeStatuses'] = self._serialize.query('include_statuses', include_statuses, 'bool')
content = self._serialize.body(search_criteria, 'GitQueryCommitsCriteria')
response = self._send(http_method='POST',
location_id='6400dfb2-0bcb-462b-b992-5a57f8f1416c',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters,
content=content)
return self._deserialize('[GitCommitRef]', self._unwrap_collection(response))
def get_deleted_repositories(self, project):
"""GetDeletedRepositories.
[Preview API] Retrieve deleted git repositories.
:param str project: Project ID or project name
:rtype: [GitDeletedRepository]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
response = self._send(http_method='GET',
location_id='2b6869c4-cb25-42b5-b7a3-0d3e6be0a11a',
version='7.1-preview.1',
route_values=route_values)
return self._deserialize('[GitDeletedRepository]', self._unwrap_collection(response))
def get_forks(self, repository_name_or_id, collection_id, project=None, include_links=None):
"""GetForks.
[Preview API] Retrieve all forks of a repository in the collection.
:param str repository_name_or_id: The name or ID of the repository.
:param str collection_id: Team project collection ID.
:param str project: Project ID or project name
:param bool include_links: True to include links.
:rtype: [GitRepositoryRef]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_name_or_id is not None:
route_values['repositoryNameOrId'] = self._serialize.url('repository_name_or_id', repository_name_or_id, 'str')
if collection_id is not None:
route_values['collectionId'] = self._serialize.url('collection_id', collection_id, 'str')
query_parameters = {}
if include_links is not None:
query_parameters['includeLinks'] = self._serialize.query('include_links', include_links, 'bool')
response = self._send(http_method='GET',
location_id='158c0340-bf6f-489c-9625-d572a1480d57',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('[GitRepositoryRef]', self._unwrap_collection(response))
def create_fork_sync_request(self, sync_params, repository_name_or_id, project=None, include_links=None):
"""CreateForkSyncRequest.
[Preview API] Request that another repository's refs be fetched into this one. It syncs two existing forks. To create a fork, please see the <a href="https://docs.microsoft.com/en-us/rest/api/vsts/git/repositories/create?view=azure-devops-rest-5.1"> repositories endpoint</a>
:param :class:`<GitForkSyncRequestParameters> <azure.devops.v7_1.git.models.GitForkSyncRequestParameters>` sync_params: Source repository and ref mapping.
:param str repository_name_or_id: The name or ID of the repository.
:param str project: Project ID or project name
:param bool include_links: True to include links
:rtype: :class:`<GitForkSyncRequest> <azure.devops.v7_1.git.models.GitForkSyncRequest>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_name_or_id is not None:
route_values['repositoryNameOrId'] = self._serialize.url('repository_name_or_id', repository_name_or_id, 'str')
query_parameters = {}
if include_links is not None:
query_parameters['includeLinks'] = self._serialize.query('include_links', include_links, 'bool')
content = self._serialize.body(sync_params, 'GitForkSyncRequestParameters')
response = self._send(http_method='POST',
location_id='1703f858-b9d1-46af-ab62-483e9e1055b5',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters,
content=content)
return self._deserialize('GitForkSyncRequest', response)
def get_fork_sync_request(self, repository_name_or_id, fork_sync_operation_id, project=None, include_links=None):
"""GetForkSyncRequest.
[Preview API] Get a specific fork sync operation's details.
:param str repository_name_or_id: The name or ID of the repository.
:param int fork_sync_operation_id: OperationId of the sync request.
:param str project: Project ID or project name
:param bool include_links: True to include links.
:rtype: :class:`<GitForkSyncRequest> <azure.devops.v7_1.git.models.GitForkSyncRequest>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_name_or_id is not None:
route_values['repositoryNameOrId'] = self._serialize.url('repository_name_or_id', repository_name_or_id, 'str')
if fork_sync_operation_id is not None:
route_values['forkSyncOperationId'] = self._serialize.url('fork_sync_operation_id', fork_sync_operation_id, 'int')
query_parameters = {}
if include_links is not None:
query_parameters['includeLinks'] = self._serialize.query('include_links', include_links, 'bool')
response = self._send(http_method='GET',
location_id='1703f858-b9d1-46af-ab62-483e9e1055b5',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('GitForkSyncRequest', response)
def get_fork_sync_requests(self, repository_name_or_id, project=None, include_abandoned=None, include_links=None):
"""GetForkSyncRequests.
[Preview API] Retrieve all requested fork sync operations on this repository.
:param str repository_name_or_id: The name or ID of the repository.
:param str project: Project ID or project name
:param bool include_abandoned: True to include abandoned requests.
:param bool include_links: True to include links.
:rtype: [GitForkSyncRequest]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_name_or_id is not None:
route_values['repositoryNameOrId'] = self._serialize.url('repository_name_or_id', repository_name_or_id, 'str')
query_parameters = {}
if include_abandoned is not None:
query_parameters['includeAbandoned'] = self._serialize.query('include_abandoned', include_abandoned, 'bool')
if include_links is not None:
query_parameters['includeLinks'] = self._serialize.query('include_links', include_links, 'bool')
response = self._send(http_method='GET',
location_id='1703f858-b9d1-46af-ab62-483e9e1055b5',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('[GitForkSyncRequest]', self._unwrap_collection(response))
def get_changes(self, commit_id, repository_id, project=None, top=None, skip=None):
"""GetChanges.
[Preview API] Retrieve changes for a particular commit.
:param str commit_id: The id of the commit.
:param str repository_id: The id or friendly name of the repository. To use the friendly name, projectId must also be specified.
:param str project: Project ID or project name
:param int top: The maximum number of changes to return.
:param int skip: The number of changes to skip.
:rtype: :class:`<GitCommitChanges> <azure.devops.v7_1.git.models.GitCommitChanges>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if commit_id is not None:
route_values['commitId'] = self._serialize.url('commit_id', commit_id, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
query_parameters = {}
if top is not None:
query_parameters['top'] = self._serialize.query('top', top, 'int')
if skip is not None:
query_parameters['skip'] = self._serialize.query('skip', skip, 'int')
response = self._send(http_method='GET',
location_id='5bf884f5-3e07-42e9-afb8-1b872267bf16',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('GitCommitChanges', response)
def create_cherry_pick(self, cherry_pick_to_create, project, repository_id):
"""CreateCherryPick.
[Preview API] Cherry pick a specific commit or commits that are associated to a pull request into a new branch.
:param :class:`<GitAsyncRefOperationParameters> <azure.devops.v7_1.git.models.GitAsyncRefOperationParameters>` cherry_pick_to_create:
:param str project: Project ID or project name
:param str repository_id: ID of the repository.
:rtype: :class:`<GitCherryPick> <azure.devops.v7_1.git.models.GitCherryPick>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
content = self._serialize.body(cherry_pick_to_create, 'GitAsyncRefOperationParameters')
response = self._send(http_method='POST',
location_id='033bad68-9a14-43d1-90e0-59cb8856fef6',
version='7.1-preview.1',
route_values=route_values,
content=content)
return self._deserialize('GitCherryPick', response)
def get_cherry_pick(self, project, cherry_pick_id, repository_id):
"""GetCherryPick.
[Preview API] Retrieve information about a cherry pick operation by cherry pick Id.
:param str project: Project ID or project name
:param int cherry_pick_id: ID of the cherry pick.
:param str repository_id: ID of the repository.
:rtype: :class:`<GitCherryPick> <azure.devops.v7_1.git.models.GitCherryPick>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if cherry_pick_id is not None:
route_values['cherryPickId'] = self._serialize.url('cherry_pick_id', cherry_pick_id, 'int')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
response = self._send(http_method='GET',
location_id='033bad68-9a14-43d1-90e0-59cb8856fef6',
version='7.1-preview.1',
route_values=route_values)
return self._deserialize('GitCherryPick', response)
def get_cherry_pick_for_ref_name(self, project, repository_id, ref_name):
"""GetCherryPickForRefName.
[Preview API] Retrieve information about a cherry pick operation for a specific branch. This operation is expensive due to the underlying object structure, so this API only looks at the 1000 most recent cherry pick operations.
:param str project: Project ID or project name
:param str repository_id: ID of the repository.
:param str ref_name: The GitAsyncRefOperationParameters generatedRefName used for the cherry pick operation.
:rtype: :class:`<GitCherryPick> <azure.devops.v7_1.git.models.GitCherryPick>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
query_parameters = {}
if ref_name is not None:
query_parameters['refName'] = self._serialize.query('ref_name', ref_name, 'str')
response = self._send(http_method='GET',
location_id='033bad68-9a14-43d1-90e0-59cb8856fef6',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('GitCherryPick', response)
def create_import_request(self, import_request, project, repository_id):
"""CreateImportRequest.
[Preview API] Create an import request.
:param :class:`<GitImportRequest> <azure.devops.v7_1.git.models.GitImportRequest>` import_request: The import request to create.
:param str project: Project ID or project name
:param str repository_id: The name or ID of the repository.
:rtype: :class:`<GitImportRequest> <azure.devops.v7_1.git.models.GitImportRequest>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
content = self._serialize.body(import_request, 'GitImportRequest')
response = self._send(http_method='POST',
location_id='01828ddc-3600-4a41-8633-99b3a73a0eb3',
version='7.1-preview.1',
route_values=route_values,
content=content)
return self._deserialize('GitImportRequest', response)
def get_import_request(self, project, repository_id, import_request_id):
"""GetImportRequest.
[Preview API] Retrieve a particular import request.
:param str project: Project ID or project name
:param str repository_id: The name or ID of the repository.
:param int import_request_id: The unique identifier for the import request.
:rtype: :class:`<GitImportRequest> <azure.devops.v7_1.git.models.GitImportRequest>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if import_request_id is not None:
route_values['importRequestId'] = self._serialize.url('import_request_id', import_request_id, 'int')
response = self._send(http_method='GET',
location_id='01828ddc-3600-4a41-8633-99b3a73a0eb3',
version='7.1-preview.1',
route_values=route_values)
return self._deserialize('GitImportRequest', response)
def query_import_requests(self, project, repository_id, include_abandoned=None):
"""QueryImportRequests.
[Preview API] Retrieve import requests for a repository.
:param str project: Project ID or project name
:param str repository_id: The name or ID of the repository.
:param bool include_abandoned: True to include abandoned import requests in the results.
:rtype: [GitImportRequest]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
query_parameters = {}
if include_abandoned is not None:
query_parameters['includeAbandoned'] = self._serialize.query('include_abandoned', include_abandoned, 'bool')
response = self._send(http_method='GET',
location_id='01828ddc-3600-4a41-8633-99b3a73a0eb3',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('[GitImportRequest]', self._unwrap_collection(response))
def update_import_request(self, import_request_to_update, project, repository_id, import_request_id):
"""UpdateImportRequest.
[Preview API] Retry or abandon a failed import request.
:param :class:`<GitImportRequest> <azure.devops.v7_1.git.models.GitImportRequest>` import_request_to_update: The updated version of the import request. Currently, the only change allowed is setting the Status to Queued or Abandoned.
:param str project: Project ID or project name
:param str repository_id: The name or ID of the repository.
:param int import_request_id: The unique identifier for the import request to update.
:rtype: :class:`<GitImportRequest> <azure.devops.v7_1.git.models.GitImportRequest>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if import_request_id is not None:
route_values['importRequestId'] = self._serialize.url('import_request_id', import_request_id, 'int')
content = self._serialize.body(import_request_to_update, 'GitImportRequest')
response = self._send(http_method='PATCH',
location_id='01828ddc-3600-4a41-8633-99b3a73a0eb3',
version='7.1-preview.1',
route_values=route_values,
content=content)
return self._deserialize('GitImportRequest', response)
def get_item(self, repository_id, path, project=None, scope_path=None, recursion_level=None, include_content_metadata=None, latest_processed_change=None, download=None, version_descriptor=None, include_content=None, resolve_lfs=None, sanitize=None):
"""GetItem.
[Preview API] Get Item Metadata and/or Content for a single item. The download parameter is to indicate whether the content should be available as a download or just sent as a stream in the response. Doesn't apply to zipped content, which is always returned as a download.
:param str repository_id: The name or ID of the repository.
:param str path: The item path.
:param str project: Project ID or project name
:param str scope_path: The path scope. The default is null.
:param str recursion_level: The recursion level of this request. The default is 'none', no recursion.
:param bool include_content_metadata: Set to true to include content metadata. Default is false.
:param bool latest_processed_change: Set to true to include the latest changes. Default is false.
:param bool download: Set to true to download the response as a file. Default is false.
:param :class:`<GitVersionDescriptor> <azure.devops.v7_1.git.models.GitVersionDescriptor>` version_descriptor: Version descriptor. Default is the default branch for the repository.
:param bool include_content: Set to true to include item content when requesting json. Default is false.
:param bool resolve_lfs: Set to true to resolve Git LFS pointer files to return actual content from Git LFS. Default is false.
:param bool sanitize: Set to true to sanitize an svg file and return it as image. Useful only if requested for svg file. Default is false.
:rtype: :class:`<GitItem> <azure.devops.v7_1.git.models.GitItem>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
query_parameters = {}
if path is not None:
query_parameters['path'] = self._serialize.query('path', path, 'str')
if scope_path is not None:
query_parameters['scopePath'] = self._serialize.query('scope_path', scope_path, 'str')
if recursion_level is not None:
query_parameters['recursionLevel'] = self._serialize.query('recursion_level', recursion_level, 'str')
if include_content_metadata is not None:
query_parameters['includeContentMetadata'] = self._serialize.query('include_content_metadata', include_content_metadata, 'bool')
if latest_processed_change is not None:
query_parameters['latestProcessedChange'] = self._serialize.query('latest_processed_change', latest_processed_change, 'bool')
if download is not None:
query_parameters['download'] = self._serialize.query('download', download, 'bool')
if version_descriptor is not None:
if version_descriptor.version_type is not None:
query_parameters['versionDescriptor.versionType'] = version_descriptor.version_type
if version_descriptor.version is not None:
query_parameters['versionDescriptor.version'] = version_descriptor.version
if version_descriptor.version_options is not None:
query_parameters['versionDescriptor.versionOptions'] = version_descriptor.version_options
if include_content is not None:
query_parameters['includeContent'] = self._serialize.query('include_content', include_content, 'bool')
if resolve_lfs is not None:
query_parameters['resolveLfs'] = self._serialize.query('resolve_lfs', resolve_lfs, 'bool')
if sanitize is not None:
query_parameters['sanitize'] = self._serialize.query('sanitize', sanitize, 'bool')
response = self._send(http_method='GET',
location_id='fb93c0db-47ed-4a31-8c20-47552878fb44',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('GitItem', response)
def get_item_content(self, repository_id, path, project=None, scope_path=None, recursion_level=None, include_content_metadata=None, latest_processed_change=None, download=None, version_descriptor=None, include_content=None, resolve_lfs=None, sanitize=None, **kwargs):
"""GetItemContent.
[Preview API] Get Item Metadata and/or Content for a single item. The download parameter is to indicate whether the content should be available as a download or just sent as a stream in the response. Doesn't apply to zipped content, which is always returned as a download.
:param str repository_id: The name or ID of the repository.
:param str path: The item path.
:param str project: Project ID or project name
:param str scope_path: The path scope. The default is null.
:param str recursion_level: The recursion level of this request. The default is 'none', no recursion.
:param bool include_content_metadata: Set to true to include content metadata. Default is false.
:param bool latest_processed_change: Set to true to include the latest changes. Default is false.
:param bool download: Set to true to download the response as a file. Default is false.
:param :class:`<GitVersionDescriptor> <azure.devops.v7_1.git.models.GitVersionDescriptor>` version_descriptor: Version descriptor. Default is the default branch for the repository.
:param bool include_content: Set to true to include item content when requesting json. Default is false.
:param bool resolve_lfs: Set to true to resolve Git LFS pointer files to return actual content from Git LFS. Default is false.
:param bool sanitize: Set to true to sanitize an svg file and return it as image. Useful only if requested for svg file. Default is false.
:rtype: object
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
query_parameters = {}
if path is not None:
query_parameters['path'] = self._serialize.query('path', path, 'str')
if scope_path is not None:
query_parameters['scopePath'] = self._serialize.query('scope_path', scope_path, 'str')
if recursion_level is not None:
query_parameters['recursionLevel'] = self._serialize.query('recursion_level', recursion_level, 'str')
if include_content_metadata is not None:
query_parameters['includeContentMetadata'] = self._serialize.query('include_content_metadata', include_content_metadata, 'bool')
if latest_processed_change is not None:
query_parameters['latestProcessedChange'] = self._serialize.query('latest_processed_change', latest_processed_change, 'bool')
if download is not None:
query_parameters['download'] = self._serialize.query('download', download, 'bool')
if version_descriptor is not None:
if version_descriptor.version_type is not None:
query_parameters['versionDescriptor.versionType'] = version_descriptor.version_type
if version_descriptor.version is not None:
query_parameters['versionDescriptor.version'] = version_descriptor.version
if version_descriptor.version_options is not None:
query_parameters['versionDescriptor.versionOptions'] = version_descriptor.version_options
if include_content is not None:
query_parameters['includeContent'] = self._serialize.query('include_content', include_content, 'bool')
if resolve_lfs is not None:
query_parameters['resolveLfs'] = self._serialize.query('resolve_lfs', resolve_lfs, 'bool')
if sanitize is not None:
query_parameters['sanitize'] = self._serialize.query('sanitize', sanitize, 'bool')
response = self._send(http_method='GET',
location_id='fb93c0db-47ed-4a31-8c20-47552878fb44',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters,
accept_media_type='application/octet-stream')
if "callback" in kwargs:
callback = kwargs["callback"]
else:
callback = None
return self._client.stream_download(response, callback=callback)
def get_items(self, repository_id, project=None, scope_path=None, recursion_level=None, include_content_metadata=None, latest_processed_change=None, download=None, include_links=None, version_descriptor=None, zip_for_unix=None):
"""GetItems.
[Preview API] Get Item Metadata and/or Content for a collection of items. The download parameter is to indicate whether the content should be available as a download or just sent as a stream in the response. Doesn't apply to zipped content which is always returned as a download.
:param str repository_id: The name or ID of the repository.
:param str project: Project ID or project name
:param str scope_path: The path scope. The default is null.
:param str recursion_level: The recursion level of this request. The default is 'none', no recursion.
:param bool include_content_metadata: Set to true to include content metadata. Default is false.
:param bool latest_processed_change: Set to true to include the latest changes. Default is false.
:param bool download: Set to true to download the response as a file. Default is false.
:param bool include_links: Set to true to include links to items. Default is false.
:param :class:`<GitVersionDescriptor> <azure.devops.v7_1.git.models.GitVersionDescriptor>` version_descriptor: Version descriptor. Default is the default branch for the repository.
:param bool zip_for_unix: Set to true to keep the file permissions for unix (and POSIX) systems like executables and symlinks
:rtype: [GitItem]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
query_parameters = {}
if scope_path is not None:
query_parameters['scopePath'] = self._serialize.query('scope_path', scope_path, 'str')
if recursion_level is not None:
query_parameters['recursionLevel'] = self._serialize.query('recursion_level', recursion_level, 'str')
if include_content_metadata is not None:
query_parameters['includeContentMetadata'] = self._serialize.query('include_content_metadata', include_content_metadata, 'bool')
if latest_processed_change is not None:
query_parameters['latestProcessedChange'] = self._serialize.query('latest_processed_change', latest_processed_change, 'bool')
if download is not None:
query_parameters['download'] = self._serialize.query('download', download, 'bool')
if include_links is not None:
query_parameters['includeLinks'] = self._serialize.query('include_links', include_links, 'bool')
if version_descriptor is not None:
if version_descriptor.version_type is not None:
query_parameters['versionDescriptor.versionType'] = version_descriptor.version_type
if version_descriptor.version is not None:
query_parameters['versionDescriptor.version'] = version_descriptor.version
if version_descriptor.version_options is not None:
query_parameters['versionDescriptor.versionOptions'] = version_descriptor.version_options
if zip_for_unix is not None:
query_parameters['zipForUnix'] = self._serialize.query('zip_for_unix', zip_for_unix, 'bool')
response = self._send(http_method='GET',
location_id='fb93c0db-47ed-4a31-8c20-47552878fb44',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('[GitItem]', self._unwrap_collection(response))
def get_item_text(self, repository_id, path, project=None, scope_path=None, recursion_level=None, include_content_metadata=None, latest_processed_change=None, download=None, version_descriptor=None, include_content=None, resolve_lfs=None, sanitize=None, **kwargs):
"""GetItemText.
[Preview API] Get Item Metadata and/or Content for a single item. The download parameter is to indicate whether the content should be available as a download or just sent as a stream in the response. Doesn't apply to zipped content, which is always returned as a download.
:param str repository_id: The name or ID of the repository.
:param str path: The item path.
:param str project: Project ID or project name
:param str scope_path: The path scope. The default is null.
:param str recursion_level: The recursion level of this request. The default is 'none', no recursion.
:param bool include_content_metadata: Set to true to include content metadata. Default is false.
:param bool latest_processed_change: Set to true to include the latest changes. Default is false.
:param bool download: Set to true to download the response as a file. Default is false.
:param :class:`<GitVersionDescriptor> <azure.devops.v7_1.git.models.GitVersionDescriptor>` version_descriptor: Version descriptor. Default is the default branch for the repository.
:param bool include_content: Set to true to include item content when requesting json. Default is false.
:param bool resolve_lfs: Set to true to resolve Git LFS pointer files to return actual content from Git LFS. Default is false.
:param bool sanitize: Set to true to sanitize an svg file and return it as image. Useful only if requested for svg file. Default is false.
:rtype: object
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
query_parameters = {}
if path is not None:
query_parameters['path'] = self._serialize.query('path', path, 'str')
if scope_path is not None:
query_parameters['scopePath'] = self._serialize.query('scope_path', scope_path, 'str')
if recursion_level is not None:
query_parameters['recursionLevel'] = self._serialize.query('recursion_level', recursion_level, 'str')
if include_content_metadata is not None:
query_parameters['includeContentMetadata'] = self._serialize.query('include_content_metadata', include_content_metadata, 'bool')
if latest_processed_change is not None:
query_parameters['latestProcessedChange'] = self._serialize.query('latest_processed_change', latest_processed_change, 'bool')
if download is not None:
query_parameters['download'] = self._serialize.query('download', download, 'bool')
if version_descriptor is not None:
if version_descriptor.version_type is not None:
query_parameters['versionDescriptor.versionType'] = version_descriptor.version_type
if version_descriptor.version is not None:
query_parameters['versionDescriptor.version'] = version_descriptor.version
if version_descriptor.version_options is not None:
query_parameters['versionDescriptor.versionOptions'] = version_descriptor.version_options
if include_content is not None:
query_parameters['includeContent'] = self._serialize.query('include_content', include_content, 'bool')
if resolve_lfs is not None:
query_parameters['resolveLfs'] = self._serialize.query('resolve_lfs', resolve_lfs, 'bool')
if sanitize is not None:
query_parameters['sanitize'] = self._serialize.query('sanitize', sanitize, 'bool')
response = self._send(http_method='GET',
location_id='fb93c0db-47ed-4a31-8c20-47552878fb44',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters,
accept_media_type='text/plain')
if "callback" in kwargs:
callback = kwargs["callback"]
else:
callback = None
return self._client.stream_download(response, callback=callback)
def get_item_zip(self, repository_id, path, project=None, scope_path=None, recursion_level=None, include_content_metadata=None, latest_processed_change=None, download=None, version_descriptor=None, include_content=None, resolve_lfs=None, sanitize=None, **kwargs):
"""GetItemZip.
[Preview API] Get Item Metadata and/or Content for a single item. The download parameter is to indicate whether the content should be available as a download or just sent as a stream in the response. Doesn't apply to zipped content, which is always returned as a download.
:param str repository_id: The name or ID of the repository.
:param str path: The item path.
:param str project: Project ID or project name
:param str scope_path: The path scope. The default is null.
:param str recursion_level: The recursion level of this request. The default is 'none', no recursion.
:param bool include_content_metadata: Set to true to include content metadata. Default is false.
:param bool latest_processed_change: Set to true to include the latest changes. Default is false.
:param bool download: Set to true to download the response as a file. Default is false.
:param :class:`<GitVersionDescriptor> <azure.devops.v7_1.git.models.GitVersionDescriptor>` version_descriptor: Version descriptor. Default is the default branch for the repository.
:param bool include_content: Set to true to include item content when requesting json. Default is false.
:param bool resolve_lfs: Set to true to resolve Git LFS pointer files to return actual content from Git LFS. Default is false.
:param bool sanitize: Set to true to sanitize an svg file and return it as image. Useful only if requested for svg file. Default is false.
:rtype: object
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
query_parameters = {}
if path is not None:
query_parameters['path'] = self._serialize.query('path', path, 'str')
if scope_path is not None:
query_parameters['scopePath'] = self._serialize.query('scope_path', scope_path, 'str')
if recursion_level is not None:
query_parameters['recursionLevel'] = self._serialize.query('recursion_level', recursion_level, 'str')
if include_content_metadata is not None:
query_parameters['includeContentMetadata'] = self._serialize.query('include_content_metadata', include_content_metadata, 'bool')
if latest_processed_change is not None:
query_parameters['latestProcessedChange'] = self._serialize.query('latest_processed_change', latest_processed_change, 'bool')
if download is not None:
query_parameters['download'] = self._serialize.query('download', download, 'bool')
if version_descriptor is not None:
if version_descriptor.version_type is not None:
query_parameters['versionDescriptor.versionType'] = version_descriptor.version_type
if version_descriptor.version is not None:
query_parameters['versionDescriptor.version'] = version_descriptor.version
if version_descriptor.version_options is not None:
query_parameters['versionDescriptor.versionOptions'] = version_descriptor.version_options
if include_content is not None:
query_parameters['includeContent'] = self._serialize.query('include_content', include_content, 'bool')
if resolve_lfs is not None:
query_parameters['resolveLfs'] = self._serialize.query('resolve_lfs', resolve_lfs, 'bool')
if sanitize is not None:
query_parameters['sanitize'] = self._serialize.query('sanitize', sanitize, 'bool')
response = self._send(http_method='GET',
location_id='fb93c0db-47ed-4a31-8c20-47552878fb44',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters,
accept_media_type='application/zip')
if "callback" in kwargs:
callback = kwargs["callback"]
else:
callback = None
return self._client.stream_download(response, callback=callback)
def get_items_batch(self, request_data, repository_id, project=None):
"""GetItemsBatch.
[Preview API] Post for retrieving a creating a batch out of a set of items in a repo / project given a list of paths or a long path
:param :class:`<GitItemRequestData> <azure.devops.v7_1.git.models.GitItemRequestData>` request_data: Request data attributes: ItemDescriptors, IncludeContentMetadata, LatestProcessedChange, IncludeLinks. ItemDescriptors: Collection of items to fetch, including path, version, and recursion level. IncludeContentMetadata: Whether to include metadata for all items LatestProcessedChange: Whether to include shallow ref to commit that last changed each item. IncludeLinks: Whether to include the _links field on the shallow references.
:param str repository_id: The name or ID of the repository
:param str project: Project ID or project name
:rtype: [[GitItem]]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
content = self._serialize.body(request_data, 'GitItemRequestData')
response = self._send(http_method='POST',
location_id='630fd2e4-fb88-4f85-ad21-13f3fd1fbca9',
version='7.1-preview.1',
route_values=route_values,
content=content)
return self._deserialize('[[GitItem]]', self._unwrap_collection(response))
def get_merge_bases(self, repository_name_or_id, commit_id, other_commit_id, project=None, other_collection_id=None, other_repository_id=None):
"""GetMergeBases.
[Preview API] Find the merge bases of two commits, optionally across forks. If otherRepositoryId is not specified, the merge bases will only be calculated within the context of the local repositoryNameOrId.
:param str repository_name_or_id: ID or name of the local repository.
:param str commit_id: First commit, usually the tip of the target branch of the potential merge.
:param str other_commit_id: Other commit, usually the tip of the source branch of the potential merge.
:param str project: Project ID or project name
:param str other_collection_id: The collection ID where otherCommitId lives.
:param str other_repository_id: The repository ID where otherCommitId lives.
:rtype: [GitCommitRef]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_name_or_id is not None:
route_values['repositoryNameOrId'] = self._serialize.url('repository_name_or_id', repository_name_or_id, 'str')
if commit_id is not None:
route_values['commitId'] = self._serialize.url('commit_id', commit_id, 'str')
query_parameters = {}
if other_commit_id is not None:
query_parameters['otherCommitId'] = self._serialize.query('other_commit_id', other_commit_id, 'str')
if other_collection_id is not None:
query_parameters['otherCollectionId'] = self._serialize.query('other_collection_id', other_collection_id, 'str')
if other_repository_id is not None:
query_parameters['otherRepositoryId'] = self._serialize.query('other_repository_id', other_repository_id, 'str')
response = self._send(http_method='GET',
location_id='7cf2abb6-c964-4f7e-9872-f78c66e72e9c',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('[GitCommitRef]', self._unwrap_collection(response))
def create_merge_request(self, merge_parameters, project, repository_name_or_id, include_links=None):
"""CreateMergeRequest.
[Preview API] Request a git merge operation. Currently we support merging only 2 commits.
:param :class:`<GitMergeParameters> <azure.devops.v7_1.git.models.GitMergeParameters>` merge_parameters: Parents commitIds and merge commit messsage.
:param str project: Project ID or project name
:param str repository_name_or_id: The name or ID of the repository.
:param bool include_links: True to include links
:rtype: :class:`<GitMerge> <azure.devops.v7_1.git.models.GitMerge>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_name_or_id is not None:
route_values['repositoryNameOrId'] = self._serialize.url('repository_name_or_id', repository_name_or_id, 'str')
query_parameters = {}
if include_links is not None:
query_parameters['includeLinks'] = self._serialize.query('include_links', include_links, 'bool')
content = self._serialize.body(merge_parameters, 'GitMergeParameters')
response = self._send(http_method='POST',
location_id='985f7ae9-844f-4906-9897-7ef41516c0e2',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters,
content=content)
return self._deserialize('GitMerge', response)
def get_merge_request(self, project, repository_name_or_id, merge_operation_id, include_links=None):
"""GetMergeRequest.
[Preview API] Get a specific merge operation's details.
:param str project: Project ID or project name
:param str repository_name_or_id: The name or ID of the repository.
:param int merge_operation_id: OperationId of the merge request.
:param bool include_links: True to include links
:rtype: :class:`<GitMerge> <azure.devops.v7_1.git.models.GitMerge>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_name_or_id is not None:
route_values['repositoryNameOrId'] = self._serialize.url('repository_name_or_id', repository_name_or_id, 'str')
if merge_operation_id is not None:
route_values['mergeOperationId'] = self._serialize.url('merge_operation_id', merge_operation_id, 'int')
query_parameters = {}
if include_links is not None:
query_parameters['includeLinks'] = self._serialize.query('include_links', include_links, 'bool')
response = self._send(http_method='GET',
location_id='985f7ae9-844f-4906-9897-7ef41516c0e2',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('GitMerge', response)
def get_policy_configurations(self, project, repository_id=None, ref_name=None, policy_type=None, top=None, continuation_token=None):
"""GetPolicyConfigurations.
[Preview API] Retrieve a list of policy configurations by a given set of scope/filtering criteria.
:param str project: Project ID or project name
:param str repository_id: The repository id.
:param str ref_name: The fully-qualified Git ref name (e.g. refs/heads/master).
:param str policy_type: The policy type filter.
:param int top: Maximum number of policies to return.
:param str continuation_token: Pass a policy configuration ID to fetch the next page of results, up to top number of results, for this endpoint.
:rtype: :class:`<GitPolicyConfigurationResponse> <azure.devops.v7_1.git.models.GitPolicyConfigurationResponse>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
query_parameters = {}
if repository_id is not None:
query_parameters['repositoryId'] = self._serialize.query('repository_id', repository_id, 'str')
if ref_name is not None:
query_parameters['refName'] = self._serialize.query('ref_name', ref_name, 'str')
if policy_type is not None:
query_parameters['policyType'] = self._serialize.query('policy_type', policy_type, 'str')
if top is not None:
query_parameters['$top'] = self._serialize.query('top', top, 'int')
if continuation_token is not None:
query_parameters['continuationToken'] = self._serialize.query('continuation_token', continuation_token, 'str')
response = self._send(http_method='GET',
location_id='2c420070-a0a2-49cc-9639-c9f271c5ff07',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters)
response_object = models.GitPolicyConfigurationResponse()
response_object.policy_configurations = self._deserialize('[PolicyConfiguration]', self._unwrap_collection(response))
response_object.continuation_token = response.headers.get('x-ms-continuationtoken')
return response_object
def create_attachment(self, upload_stream, file_name, repository_id, pull_request_id, project=None, **kwargs):
"""CreateAttachment.
[Preview API] Attach a new file to a pull request.
:param object upload_stream: Stream to upload
:param str file_name: The name of the file.
:param str repository_id: The repository ID of the pull request’s target branch.
:param int pull_request_id: ID of the pull request.
:param str project: Project ID or project name
:rtype: :class:`<Attachment> <azure.devops.v7_1.git.models.Attachment>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if file_name is not None:
route_values['fileName'] = self._serialize.url('file_name', file_name, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
if "callback" in kwargs:
callback = kwargs["callback"]
else:
callback = None
content = self._client.stream_upload(upload_stream, callback=callback)
response = self._send(http_method='POST',
location_id='965d9361-878b-413b-a494-45d5b5fd8ab7',
version='7.1-preview.1',
route_values=route_values,
content=content,
media_type='application/octet-stream')
return self._deserialize('Attachment', response)
def delete_attachment(self, file_name, repository_id, pull_request_id, project=None):
"""DeleteAttachment.
[Preview API] Delete a pull request attachment.
:param str file_name: The name of the attachment to delete.
:param str repository_id: The repository ID of the pull request’s target branch.
:param int pull_request_id: ID of the pull request.
:param str project: Project ID or project name
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if file_name is not None:
route_values['fileName'] = self._serialize.url('file_name', file_name, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
self._send(http_method='DELETE',
location_id='965d9361-878b-413b-a494-45d5b5fd8ab7',
version='7.1-preview.1',
route_values=route_values)
def get_attachment_content(self, file_name, repository_id, pull_request_id, project=None, **kwargs):
"""GetAttachmentContent.
[Preview API] Get the file content of a pull request attachment.
:param str file_name: The name of the attachment.
:param str repository_id: The repository ID of the pull request’s target branch.
:param int pull_request_id: ID of the pull request.
:param str project: Project ID or project name
:rtype: object
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if file_name is not None:
route_values['fileName'] = self._serialize.url('file_name', file_name, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
response = self._send(http_method='GET',
location_id='965d9361-878b-413b-a494-45d5b5fd8ab7',
version='7.1-preview.1',
route_values=route_values,
accept_media_type='application/octet-stream')
if "callback" in kwargs:
callback = kwargs["callback"]
else:
callback = None
return self._client.stream_download(response, callback=callback)
def get_attachments(self, repository_id, pull_request_id, project=None):
"""GetAttachments.
[Preview API] Get a list of files attached to a given pull request.
:param str repository_id: The repository ID of the pull request’s target branch.
:param int pull_request_id: ID of the pull request.
:param str project: Project ID or project name
:rtype: [Attachment]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
response = self._send(http_method='GET',
location_id='965d9361-878b-413b-a494-45d5b5fd8ab7',
version='7.1-preview.1',
route_values=route_values)
return self._deserialize('[Attachment]', self._unwrap_collection(response))
def get_attachment_zip(self, file_name, repository_id, pull_request_id, project=None, **kwargs):
"""GetAttachmentZip.
[Preview API] Get the file content of a pull request attachment.
:param str file_name: The name of the attachment.
:param str repository_id: The repository ID of the pull request’s target branch.
:param int pull_request_id: ID of the pull request.
:param str project: Project ID or project name
:rtype: object
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if file_name is not None:
route_values['fileName'] = self._serialize.url('file_name', file_name, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
response = self._send(http_method='GET',
location_id='965d9361-878b-413b-a494-45d5b5fd8ab7',
version='7.1-preview.1',
route_values=route_values,
accept_media_type='application/zip')
if "callback" in kwargs:
callback = kwargs["callback"]
else:
callback = None
return self._client.stream_download(response, callback=callback)
def create_like(self, repository_id, pull_request_id, thread_id, comment_id, project=None):
"""CreateLike.
[Preview API] Add a like on a comment.
:param str repository_id: The repository ID of the pull request's target branch.
:param int pull_request_id: ID of the pull request.
:param int thread_id: The ID of the thread that contains the comment.
:param int comment_id: The ID of the comment.
:param str project: Project ID or project name
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
if thread_id is not None:
route_values['threadId'] = self._serialize.url('thread_id', thread_id, 'int')
if comment_id is not None:
route_values['commentId'] = self._serialize.url('comment_id', comment_id, 'int')
self._send(http_method='POST',
location_id='5f2e2851-1389-425b-a00b-fb2adb3ef31b',
version='7.1-preview.1',
route_values=route_values)
def delete_like(self, repository_id, pull_request_id, thread_id, comment_id, project=None):
"""DeleteLike.
[Preview API] Delete a like on a comment.
:param str repository_id: The repository ID of the pull request's target branch.
:param int pull_request_id: ID of the pull request.
:param int thread_id: The ID of the thread that contains the comment.
:param int comment_id: The ID of the comment.
:param str project: Project ID or project name
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
if thread_id is not None:
route_values['threadId'] = self._serialize.url('thread_id', thread_id, 'int')
if comment_id is not None:
route_values['commentId'] = self._serialize.url('comment_id', comment_id, 'int')
self._send(http_method='DELETE',
location_id='5f2e2851-1389-425b-a00b-fb2adb3ef31b',
version='7.1-preview.1',
route_values=route_values)
def get_likes(self, repository_id, pull_request_id, thread_id, comment_id, project=None):
"""GetLikes.
[Preview API] Get likes for a comment.
:param str repository_id: The repository ID of the pull request's target branch.
:param int pull_request_id: ID of the pull request.
:param int thread_id: The ID of the thread that contains the comment.
:param int comment_id: The ID of the comment.
:param str project: Project ID or project name
:rtype: [IdentityRef]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
if thread_id is not None:
route_values['threadId'] = self._serialize.url('thread_id', thread_id, 'int')
if comment_id is not None:
route_values['commentId'] = self._serialize.url('comment_id', comment_id, 'int')
response = self._send(http_method='GET',
location_id='5f2e2851-1389-425b-a00b-fb2adb3ef31b',
version='7.1-preview.1',
route_values=route_values)
return self._deserialize('[IdentityRef]', self._unwrap_collection(response))
def get_pull_request_iteration_commits(self, repository_id, pull_request_id, iteration_id, project=None, top=None, skip=None):
"""GetPullRequestIterationCommits.
[Preview API] Get the commits for the specified iteration of a pull request.
:param str repository_id: ID or name of the repository.
:param int pull_request_id: ID of the pull request.
:param int iteration_id: ID of the iteration from which to get the commits.
:param str project: Project ID or project name
:param int top: Maximum number of commits to return. The maximum number of commits that can be returned per batch is 500.
:param int skip: Number of commits to skip.
:rtype: [GitCommitRef]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
if iteration_id is not None:
route_values['iterationId'] = self._serialize.url('iteration_id', iteration_id, 'int')
query_parameters = {}
if top is not None:
query_parameters['top'] = self._serialize.query('top', top, 'int')
if skip is not None:
query_parameters['skip'] = self._serialize.query('skip', skip, 'int')
response = self._send(http_method='GET',
location_id='e7ea0883-095f-4926-b5fb-f24691c26fb9',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('[GitCommitRef]', self._unwrap_collection(response))
def get_pull_request_commits(self, repository_id, pull_request_id, project=None, top=None, continuation_token=None):
"""GetPullRequestCommits.
[Preview API] Get the commits for the specified pull request.
:param str repository_id: ID or name of the repository.
:param int pull_request_id: ID of the pull request.
:param str project: Project ID or project name
:param int top: Maximum number of commits to return.
:param str continuation_token: The continuation token used for pagination.
:rtype: :class:`<[GitCommitRef]> <azure.devops.v7_1.git.models.[GitCommitRef]>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
query_parameters = {}
if top is not None:
query_parameters['$top'] = self._serialize.query('top', top, 'int')
if continuation_token is not None:
query_parameters['continuationToken'] = self._serialize.query('continuation_token', continuation_token, 'str')
response = self._send(http_method='GET',
location_id='52823034-34a8-4576-922c-8d8b77e9e4c4',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('[GitCommitRef]', self._unwrap_collection(response))
def get_pull_request_iteration_changes(self, repository_id, pull_request_id, iteration_id, project=None, top=None, skip=None, compare_to=None):
"""GetPullRequestIterationChanges.
[Preview API] Retrieve the changes made in a pull request between two iterations.
:param str repository_id: The repository ID of the pull request's target branch.
:param int pull_request_id: ID of the pull request.
:param int iteration_id: ID of the pull request iteration. <br /> Iteration one is the head of the source branch at the time the pull request is created and subsequent iterations are created when there are pushes to the source branch. Allowed values are between 1 and the maximum iteration on this pull request.
:param str project: Project ID or project name
:param int top: Optional. The number of changes to retrieve. The default value is 100 and the maximum value is 2000.
:param int skip: Optional. The number of changes to ignore. For example, to retrieve changes 101-150, set top 50 and skip to 100.
:param int compare_to: ID of the pull request iteration to compare against. The default value is zero which indicates the comparison is made against the common commit between the source and target branches
:rtype: :class:`<GitPullRequestIterationChanges> <azure.devops.v7_1.git.models.GitPullRequestIterationChanges>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
if iteration_id is not None:
route_values['iterationId'] = self._serialize.url('iteration_id', iteration_id, 'int')
query_parameters = {}
if top is not None:
query_parameters['$top'] = self._serialize.query('top', top, 'int')
if skip is not None:
query_parameters['$skip'] = self._serialize.query('skip', skip, 'int')
if compare_to is not None:
query_parameters['$compareTo'] = self._serialize.query('compare_to', compare_to, 'int')
response = self._send(http_method='GET',
location_id='4216bdcf-b6b1-4d59-8b82-c34cc183fc8b',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('GitPullRequestIterationChanges', response)
def get_pull_request_iteration(self, repository_id, pull_request_id, iteration_id, project=None):
"""GetPullRequestIteration.
[Preview API] Get the specified iteration for a pull request.
:param str repository_id: ID or name of the repository.
:param int pull_request_id: ID of the pull request.
:param int iteration_id: ID of the pull request iteration to return.
:param str project: Project ID or project name
:rtype: :class:`<GitPullRequestIteration> <azure.devops.v7_1.git.models.GitPullRequestIteration>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
if iteration_id is not None:
route_values['iterationId'] = self._serialize.url('iteration_id', iteration_id, 'int')
response = self._send(http_method='GET',
location_id='d43911ee-6958-46b0-a42b-8445b8a0d004',
version='7.1-preview.2',
route_values=route_values)
return self._deserialize('GitPullRequestIteration', response)
def get_pull_request_iterations(self, repository_id, pull_request_id, project=None, include_commits=None):
"""GetPullRequestIterations.
[Preview API] Get the list of iterations for the specified pull request.
:param str repository_id: ID or name of the repository.
:param int pull_request_id: ID of the pull request.
:param str project: Project ID or project name
:param bool include_commits: If true, include the commits associated with each iteration in the response.
:rtype: [GitPullRequestIteration]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
query_parameters = {}
if include_commits is not None:
query_parameters['includeCommits'] = self._serialize.query('include_commits', include_commits, 'bool')
response = self._send(http_method='GET',
location_id='d43911ee-6958-46b0-a42b-8445b8a0d004',
version='7.1-preview.2',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('[GitPullRequestIteration]', self._unwrap_collection(response))
def create_pull_request_iteration_status(self, status, repository_id, pull_request_id, iteration_id, project=None):
"""CreatePullRequestIterationStatus.
[Preview API] Create a pull request status on the iteration. This operation will have the same result as Create status on pull request with specified iteration ID in the request body.
:param :class:`<GitPullRequestStatus> <azure.devops.v7_1.git.models.GitPullRequestStatus>` status: Pull request status to create.
:param str repository_id: The repository ID of the pull request’s target branch.
:param int pull_request_id: ID of the pull request.
:param int iteration_id: ID of the pull request iteration.
:param str project: Project ID or project name
:rtype: :class:`<GitPullRequestStatus> <azure.devops.v7_1.git.models.GitPullRequestStatus>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
if iteration_id is not None:
route_values['iterationId'] = self._serialize.url('iteration_id', iteration_id, 'int')
content = self._serialize.body(status, 'GitPullRequestStatus')
response = self._send(http_method='POST',
location_id='75cf11c5-979f-4038-a76e-058a06adf2bf',
version='7.1-preview.1',
route_values=route_values,
content=content)
return self._deserialize('GitPullRequestStatus', response)
def delete_pull_request_iteration_status(self, repository_id, pull_request_id, iteration_id, status_id, project=None):
"""DeletePullRequestIterationStatus.
[Preview API] Delete pull request iteration status.
:param str repository_id: The repository ID of the pull request’s target branch.
:param int pull_request_id: ID of the pull request.
:param int iteration_id: ID of the pull request iteration.
:param int status_id: ID of the pull request status.
:param str project: Project ID or project name
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
if iteration_id is not None:
route_values['iterationId'] = self._serialize.url('iteration_id', iteration_id, 'int')
if status_id is not None:
route_values['statusId'] = self._serialize.url('status_id', status_id, 'int')
self._send(http_method='DELETE',
location_id='75cf11c5-979f-4038-a76e-058a06adf2bf',
version='7.1-preview.1',
route_values=route_values)
def get_pull_request_iteration_status(self, repository_id, pull_request_id, iteration_id, status_id, project=None):
"""GetPullRequestIterationStatus.
[Preview API] Get the specific pull request iteration status by ID. The status ID is unique within the pull request across all iterations.
:param str repository_id: The repository ID of the pull request’s target branch.
:param int pull_request_id: ID of the pull request.
:param int iteration_id: ID of the pull request iteration.
:param int status_id: ID of the pull request status.
:param str project: Project ID or project name
:rtype: :class:`<GitPullRequestStatus> <azure.devops.v7_1.git.models.GitPullRequestStatus>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
if iteration_id is not None:
route_values['iterationId'] = self._serialize.url('iteration_id', iteration_id, 'int')
if status_id is not None:
route_values['statusId'] = self._serialize.url('status_id', status_id, 'int')
response = self._send(http_method='GET',
location_id='75cf11c5-979f-4038-a76e-058a06adf2bf',
version='7.1-preview.1',
route_values=route_values)
return self._deserialize('GitPullRequestStatus', response)
def get_pull_request_iteration_statuses(self, repository_id, pull_request_id, iteration_id, project=None):
"""GetPullRequestIterationStatuses.
[Preview API] Get all the statuses associated with a pull request iteration.
:param str repository_id: The repository ID of the pull request’s target branch.
:param int pull_request_id: ID of the pull request.
:param int iteration_id: ID of the pull request iteration.
:param str project: Project ID or project name
:rtype: [GitPullRequestStatus]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
if iteration_id is not None:
route_values['iterationId'] = self._serialize.url('iteration_id', iteration_id, 'int')
response = self._send(http_method='GET',
location_id='75cf11c5-979f-4038-a76e-058a06adf2bf',
version='7.1-preview.1',
route_values=route_values)
return self._deserialize('[GitPullRequestStatus]', self._unwrap_collection(response))
def update_pull_request_iteration_statuses(self, patch_document, repository_id, pull_request_id, iteration_id, project=None):
"""UpdatePullRequestIterationStatuses.
[Preview API] Update pull request iteration statuses collection. The only supported operation type is `remove`.
:param :class:`<[JsonPatchOperation]> <azure.devops.v7_1.git.models.[JsonPatchOperation]>` patch_document: Operations to apply to the pull request statuses in JSON Patch format.
:param str repository_id: The repository ID of the pull request’s target branch.
:param int pull_request_id: ID of the pull request.
:param int iteration_id: ID of the pull request iteration.
:param str project: Project ID or project name
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
if iteration_id is not None:
route_values['iterationId'] = self._serialize.url('iteration_id', iteration_id, 'int')
content = self._serialize.body(patch_document, '[JsonPatchOperation]')
self._send(http_method='PATCH',
location_id='75cf11c5-979f-4038-a76e-058a06adf2bf',
version='7.1-preview.1',
route_values=route_values,
content=content,
media_type='application/json-patch+json')
def create_pull_request_label(self, label, repository_id, pull_request_id, project=None, project_id=None):
"""CreatePullRequestLabel.
[Preview API] Create a label for a specified pull request. The only required field is the name of the new label.
:param :class:`<WebApiCreateTagRequestData> <azure.devops.v7_1.git.models.WebApiCreateTagRequestData>` label: Label to assign to the pull request.
:param str repository_id: The repository ID of the pull request’s target branch.
:param int pull_request_id: ID of the pull request.
:param str project: Project ID or project name
:param str project_id: Project ID or project name.
:rtype: :class:`<WebApiTagDefinition> <azure.devops.v7_1.git.models.WebApiTagDefinition>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
query_parameters = {}
if project_id is not None:
query_parameters['projectId'] = self._serialize.query('project_id', project_id, 'str')
content = self._serialize.body(label, 'WebApiCreateTagRequestData')
response = self._send(http_method='POST',
location_id='f22387e3-984e-4c52-9c6d-fbb8f14c812d',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters,
content=content)
return self._deserialize('WebApiTagDefinition', response)
def delete_pull_request_labels(self, repository_id, pull_request_id, label_id_or_name, project=None, project_id=None):
"""DeletePullRequestLabels.
[Preview API] Removes a label from the set of those assigned to the pull request.
:param str repository_id: The repository ID of the pull request’s target branch.
:param int pull_request_id: ID of the pull request.
:param str label_id_or_name: The name or ID of the label requested.
:param str project: Project ID or project name
:param str project_id: Project ID or project name.
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
if label_id_or_name is not None:
route_values['labelIdOrName'] = self._serialize.url('label_id_or_name', label_id_or_name, 'str')
query_parameters = {}
if project_id is not None:
query_parameters['projectId'] = self._serialize.query('project_id', project_id, 'str')
self._send(http_method='DELETE',
location_id='f22387e3-984e-4c52-9c6d-fbb8f14c812d',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters)
def get_pull_request_label(self, repository_id, pull_request_id, label_id_or_name, project=None, project_id=None):
"""GetPullRequestLabel.
[Preview API] Retrieves a single label that has been assigned to a pull request.
:param str repository_id: The repository ID of the pull request’s target branch.
:param int pull_request_id: ID of the pull request.
:param str label_id_or_name: The name or ID of the label requested.
:param str project: Project ID or project name
:param str project_id: Project ID or project name.
:rtype: :class:`<WebApiTagDefinition> <azure.devops.v7_1.git.models.WebApiTagDefinition>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
if label_id_or_name is not None:
route_values['labelIdOrName'] = self._serialize.url('label_id_or_name', label_id_or_name, 'str')
query_parameters = {}
if project_id is not None:
query_parameters['projectId'] = self._serialize.query('project_id', project_id, 'str')
response = self._send(http_method='GET',
location_id='f22387e3-984e-4c52-9c6d-fbb8f14c812d',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('WebApiTagDefinition', response)
def get_pull_request_labels(self, repository_id, pull_request_id, project=None, project_id=None):
"""GetPullRequestLabels.
[Preview API] Get all the labels assigned to a pull request.
:param str repository_id: The repository ID of the pull request’s target branch.
:param int pull_request_id: ID of the pull request.
:param str project: Project ID or project name
:param str project_id: Project ID or project name.
:rtype: [WebApiTagDefinition]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
query_parameters = {}
if project_id is not None:
query_parameters['projectId'] = self._serialize.query('project_id', project_id, 'str')
response = self._send(http_method='GET',
location_id='f22387e3-984e-4c52-9c6d-fbb8f14c812d',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('[WebApiTagDefinition]', self._unwrap_collection(response))
def get_pull_request_properties(self, repository_id, pull_request_id, project=None):
"""GetPullRequestProperties.
[Preview API] Get external properties of the pull request.
:param str repository_id: The repository ID of the pull request’s target branch.
:param int pull_request_id: ID of the pull request.
:param str project: Project ID or project name
:rtype: :class:`<object> <azure.devops.v7_1.git.models.object>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
response = self._send(http_method='GET',
location_id='48a52185-5b9e-4736-9dc1-bb1e2feac80b',
version='7.1-preview.1',
route_values=route_values)
return self._deserialize('object', response)
def update_pull_request_properties(self, patch_document, repository_id, pull_request_id, project=None):
"""UpdatePullRequestProperties.
[Preview API] Create or update pull request external properties. The patch operation can be `add`, `replace` or `remove`. For `add` operation, the path can be empty. If the path is empty, the value must be a list of key value pairs. For `replace` operation, the path cannot be empty. If the path does not exist, the property will be added to the collection. For `remove` operation, the path cannot be empty. If the path does not exist, no action will be performed.
:param :class:`<[JsonPatchOperation]> <azure.devops.v7_1.git.models.[JsonPatchOperation]>` patch_document: Properties to add, replace or remove in JSON Patch format.
:param str repository_id: The repository ID of the pull request’s target branch.
:param int pull_request_id: ID of the pull request.
:param str project: Project ID or project name
:rtype: :class:`<object> <azure.devops.v7_1.git.models.object>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
content = self._serialize.body(patch_document, '[JsonPatchOperation]')
response = self._send(http_method='PATCH',
location_id='48a52185-5b9e-4736-9dc1-bb1e2feac80b',
version='7.1-preview.1',
route_values=route_values,
content=content,
media_type='application/json-patch+json')
return self._deserialize('object', response)
def get_pull_request_query(self, queries, repository_id, project=None):
"""GetPullRequestQuery.
[Preview API] This API is used to find what pull requests are related to a given commit. It can be used to either find the pull request that created a particular merge commit or it can be used to find all pull requests that have ever merged a particular commit. The input is a list of queries which each contain a list of commits. For each commit that you search against, you will get back a dictionary of commit -> pull requests.
:param :class:`<GitPullRequestQuery> <azure.devops.v7_1.git.models.GitPullRequestQuery>` queries: The list of queries to perform.
:param str repository_id: ID of the repository.
:param str project: Project ID or project name
:rtype: :class:`<GitPullRequestQuery> <azure.devops.v7_1.git.models.GitPullRequestQuery>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
content = self._serialize.body(queries, 'GitPullRequestQuery')
response = self._send(http_method='POST',
location_id='b3a6eebe-9cf0-49ea-b6cb-1a4c5f5007b0',
version='7.1-preview.1',
route_values=route_values,
content=content)
return self._deserialize('GitPullRequestQuery', response)
def create_pull_request_reviewer(self, reviewer, repository_id, pull_request_id, reviewer_id, project=None):
"""CreatePullRequestReviewer.
[Preview API] Add a reviewer to a pull request or cast a vote.
:param :class:`<IdentityRefWithVote> <azure.devops.v7_1.git.models.IdentityRefWithVote>` reviewer: Reviewer's vote.<br />If the reviewer's ID is included here, it must match the reviewerID parameter.<br />Reviewers can set their own vote with this method. When adding other reviewers, vote must be set to zero.
:param str repository_id: The repository ID of the pull request's target branch.
:param int pull_request_id: ID of the pull request.
:param str reviewer_id: ID of the reviewer.
:param str project: Project ID or project name
:rtype: :class:`<IdentityRefWithVote> <azure.devops.v7_1.git.models.IdentityRefWithVote>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
if reviewer_id is not None:
route_values['reviewerId'] = self._serialize.url('reviewer_id', reviewer_id, 'str')
content = self._serialize.body(reviewer, 'IdentityRefWithVote')
response = self._send(http_method='PUT',
location_id='4b6702c7-aa35-4b89-9c96-b9abf6d3e540',
version='7.1-preview.1',
route_values=route_values,
content=content)
return self._deserialize('IdentityRefWithVote', response)
def create_pull_request_reviewers(self, reviewers, repository_id, pull_request_id, project=None):
"""CreatePullRequestReviewers.
[Preview API] Add reviewers to a pull request.
:param [IdentityRef] reviewers: Reviewers to add to the pull request.
:param str repository_id: The repository ID of the pull request's target branch.
:param int pull_request_id: ID of the pull request.
:param str project: Project ID or project name
:rtype: [IdentityRefWithVote]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
content = self._serialize.body(reviewers, '[IdentityRef]')
response = self._send(http_method='POST',
location_id='4b6702c7-aa35-4b89-9c96-b9abf6d3e540',
version='7.1-preview.1',
route_values=route_values,
content=content)
return self._deserialize('[IdentityRefWithVote]', self._unwrap_collection(response))
def create_unmaterialized_pull_request_reviewer(self, reviewer, repository_id, pull_request_id, project=None):
"""CreateUnmaterializedPullRequestReviewer.
[Preview API] Add an unmaterialized identity to the reviewers of a pull request.
:param :class:`<IdentityRefWithVote> <azure.devops.v7_1.git.models.IdentityRefWithVote>` reviewer: Reviewer to add to the pull request.
:param str repository_id: The repository ID of the pull request's target branch.
:param int pull_request_id: ID of the pull request.
:param str project: Project ID or project name
:rtype: :class:`<IdentityRefWithVote> <azure.devops.v7_1.git.models.IdentityRefWithVote>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
content = self._serialize.body(reviewer, 'IdentityRefWithVote')
response = self._send(http_method='PUT',
location_id='4b6702c7-aa35-4b89-9c96-b9abf6d3e540',
version='7.1-preview.1',
route_values=route_values,
content=content)
return self._deserialize('IdentityRefWithVote', response)
def delete_pull_request_reviewer(self, repository_id, pull_request_id, reviewer_id, project=None):
"""DeletePullRequestReviewer.
[Preview API] Remove a reviewer from a pull request.
:param str repository_id: The repository ID of the pull request's target branch.
:param int pull_request_id: ID of the pull request.
:param str reviewer_id: ID of the reviewer to remove.
:param str project: Project ID or project name
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
if reviewer_id is not None:
route_values['reviewerId'] = self._serialize.url('reviewer_id', reviewer_id, 'str')
self._send(http_method='DELETE',
location_id='4b6702c7-aa35-4b89-9c96-b9abf6d3e540',
version='7.1-preview.1',
route_values=route_values)
def get_pull_request_reviewer(self, repository_id, pull_request_id, reviewer_id, project=None):
"""GetPullRequestReviewer.
[Preview API] Retrieve information about a particular reviewer on a pull request
:param str repository_id: The repository ID of the pull request's target branch.
:param int pull_request_id: ID of the pull request.
:param str reviewer_id: ID of the reviewer.
:param str project: Project ID or project name
:rtype: :class:`<IdentityRefWithVote> <azure.devops.v7_1.git.models.IdentityRefWithVote>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
if reviewer_id is not None:
route_values['reviewerId'] = self._serialize.url('reviewer_id', reviewer_id, 'str')
response = self._send(http_method='GET',
location_id='4b6702c7-aa35-4b89-9c96-b9abf6d3e540',
version='7.1-preview.1',
route_values=route_values)
return self._deserialize('IdentityRefWithVote', response)
def get_pull_request_reviewers(self, repository_id, pull_request_id, project=None):
"""GetPullRequestReviewers.
[Preview API] Retrieve the reviewers for a pull request
:param str repository_id: The repository ID of the pull request's target branch.
:param int pull_request_id: ID of the pull request.
:param str project: Project ID or project name
:rtype: [IdentityRefWithVote]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
response = self._send(http_method='GET',
location_id='4b6702c7-aa35-4b89-9c96-b9abf6d3e540',
version='7.1-preview.1',
route_values=route_values)
return self._deserialize('[IdentityRefWithVote]', self._unwrap_collection(response))
def update_pull_request_reviewer(self, reviewer, repository_id, pull_request_id, reviewer_id, project=None):
"""UpdatePullRequestReviewer.
[Preview API] Edit a reviewer entry. These fields are patchable: isFlagged, hasDeclined
:param :class:`<IdentityRefWithVote> <azure.devops.v7_1.git.models.IdentityRefWithVote>` reviewer: Reviewer data.<br />If the reviewer's ID is included here, it must match the reviewerID parameter.
:param str repository_id: The repository ID of the pull request's target branch.
:param int pull_request_id: ID of the pull request.
:param str reviewer_id: ID of the reviewer.
:param str project: Project ID or project name
:rtype: :class:`<IdentityRefWithVote> <azure.devops.v7_1.git.models.IdentityRefWithVote>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
if reviewer_id is not None:
route_values['reviewerId'] = self._serialize.url('reviewer_id', reviewer_id, 'str')
content = self._serialize.body(reviewer, 'IdentityRefWithVote')
response = self._send(http_method='PATCH',
location_id='4b6702c7-aa35-4b89-9c96-b9abf6d3e540',
version='7.1-preview.1',
route_values=route_values,
content=content)
return self._deserialize('IdentityRefWithVote', response)
def update_pull_request_reviewers(self, patch_votes, repository_id, pull_request_id, project=None):
"""UpdatePullRequestReviewers.
[Preview API] Reset the votes of multiple reviewers on a pull request. NOTE: This endpoint only supports updating votes, but does not support updating required reviewers (use policy) or display names.
:param [IdentityRefWithVote] patch_votes: IDs of the reviewers whose votes will be reset to zero
:param str repository_id: The repository ID of the pull request's target branch.
:param int pull_request_id: ID of the pull request
:param str project: Project ID or project name
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
content = self._serialize.body(patch_votes, '[IdentityRefWithVote]')
self._send(http_method='PATCH',
location_id='4b6702c7-aa35-4b89-9c96-b9abf6d3e540',
version='7.1-preview.1',
route_values=route_values,
content=content)
def get_pull_request_by_id(self, pull_request_id, project=None):
"""GetPullRequestById.
[Preview API] Retrieve a pull request.
:param int pull_request_id: The ID of the pull request to retrieve.
:param str project: Project ID or project name
:rtype: :class:`<GitPullRequest> <azure.devops.v7_1.git.models.GitPullRequest>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
response = self._send(http_method='GET',
location_id='01a46dea-7d46-4d40-bc84-319e7c260d99',
version='7.1-preview.1',
route_values=route_values)
return self._deserialize('GitPullRequest', response)
def get_pull_requests_by_project(self, project, search_criteria, max_comment_length=None, skip=None, top=None):
"""GetPullRequestsByProject.
[Preview API] Retrieve all pull requests matching a specified criteria.
:param str project: Project ID or project name
:param :class:`<GitPullRequestSearchCriteria> <azure.devops.v7_1.git.models.GitPullRequestSearchCriteria>` search_criteria: Pull requests will be returned that match this search criteria.
:param int max_comment_length: Not used.
:param int skip: The number of pull requests to ignore. For example, to retrieve results 101-150, set top to 50 and skip to 100.
:param int top: The number of pull requests to retrieve.
:rtype: [GitPullRequest]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
query_parameters = {}
if search_criteria is not None:
if search_criteria.repository_id is not None:
query_parameters['searchCriteria.repositoryId'] = search_criteria.repository_id
if search_criteria.creator_id is not None:
query_parameters['searchCriteria.creatorId'] = search_criteria.creator_id
if search_criteria.reviewer_id is not None:
query_parameters['searchCriteria.reviewerId'] = search_criteria.reviewer_id
if search_criteria.status is not None:
query_parameters['searchCriteria.status'] = search_criteria.status
if search_criteria.target_ref_name is not None:
query_parameters['searchCriteria.targetRefName'] = search_criteria.target_ref_name
if search_criteria.source_repository_id is not None:
query_parameters['searchCriteria.sourceRepositoryId'] = search_criteria.source_repository_id
if search_criteria.source_ref_name is not None:
query_parameters['searchCriteria.sourceRefName'] = search_criteria.source_ref_name
if search_criteria.include_links is not None:
query_parameters['searchCriteria.includeLinks'] = search_criteria.include_links
if max_comment_length is not None:
query_parameters['maxCommentLength'] = self._serialize.query('max_comment_length', max_comment_length, 'int')
if skip is not None:
query_parameters['$skip'] = self._serialize.query('skip', skip, 'int')
if top is not None:
query_parameters['$top'] = self._serialize.query('top', top, 'int')
response = self._send(http_method='GET',
location_id='a5d28130-9cd2-40fa-9f08-902e7daa9efb',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('[GitPullRequest]', self._unwrap_collection(response))
def create_pull_request(self, git_pull_request_to_create, repository_id, project=None, supports_iterations=None):
"""CreatePullRequest.
[Preview API] Create a pull request.
:param :class:`<GitPullRequest> <azure.devops.v7_1.git.models.GitPullRequest>` git_pull_request_to_create: The pull request to create.
:param str repository_id: The repository ID of the pull request's target branch.
:param str project: Project ID or project name
:param bool supports_iterations: If true, subsequent pushes to the pull request will be individually reviewable. Set this to false for large pull requests for performance reasons if this functionality is not needed.
:rtype: :class:`<GitPullRequest> <azure.devops.v7_1.git.models.GitPullRequest>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
query_parameters = {}
if supports_iterations is not None:
query_parameters['supportsIterations'] = self._serialize.query('supports_iterations', supports_iterations, 'bool')
content = self._serialize.body(git_pull_request_to_create, 'GitPullRequest')
response = self._send(http_method='POST',
location_id='9946fd70-0d40-406e-b686-b4744cbbcc37',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters,
content=content)
return self._deserialize('GitPullRequest', response)
def get_pull_request(self, repository_id, pull_request_id, project=None, max_comment_length=None, skip=None, top=None, include_commits=None, include_work_item_refs=None):
"""GetPullRequest.
[Preview API] Retrieve a pull request.
:param str repository_id: The repository ID of the pull request's target branch.
:param int pull_request_id: The ID of the pull request to retrieve.
:param str project: Project ID or project name
:param int max_comment_length: Not used.
:param int skip: Not used.
:param int top: Not used.
:param bool include_commits: If true, the pull request will be returned with the associated commits.
:param bool include_work_item_refs: If true, the pull request will be returned with the associated work item references.
:rtype: :class:`<GitPullRequest> <azure.devops.v7_1.git.models.GitPullRequest>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
query_parameters = {}
if max_comment_length is not None:
query_parameters['maxCommentLength'] = self._serialize.query('max_comment_length', max_comment_length, 'int')
if skip is not None:
query_parameters['$skip'] = self._serialize.query('skip', skip, 'int')
if top is not None:
query_parameters['$top'] = self._serialize.query('top', top, 'int')
if include_commits is not None:
query_parameters['includeCommits'] = self._serialize.query('include_commits', include_commits, 'bool')
if include_work_item_refs is not None:
query_parameters['includeWorkItemRefs'] = self._serialize.query('include_work_item_refs', include_work_item_refs, 'bool')
response = self._send(http_method='GET',
location_id='9946fd70-0d40-406e-b686-b4744cbbcc37',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('GitPullRequest', response)
def get_pull_requests(self, repository_id, search_criteria, project=None, max_comment_length=None, skip=None, top=None):
"""GetPullRequests.
[Preview API] Retrieve all pull requests matching a specified criteria.
:param str repository_id: The repository ID of the pull request's target branch.
:param :class:`<GitPullRequestSearchCriteria> <azure.devops.v7_1.git.models.GitPullRequestSearchCriteria>` search_criteria: Pull requests will be returned that match this search criteria.
:param str project: Project ID or project name
:param int max_comment_length: Not used.
:param int skip: The number of pull requests to ignore. For example, to retrieve results 101-150, set top to 50 and skip to 100.
:param int top: The number of pull requests to retrieve.
:rtype: [GitPullRequest]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
query_parameters = {}
if search_criteria is not None:
if search_criteria.repository_id is not None:
query_parameters['searchCriteria.repositoryId'] = search_criteria.repository_id
if search_criteria.creator_id is not None:
query_parameters['searchCriteria.creatorId'] = search_criteria.creator_id
if search_criteria.reviewer_id is not None:
query_parameters['searchCriteria.reviewerId'] = search_criteria.reviewer_id
if search_criteria.status is not None:
query_parameters['searchCriteria.status'] = search_criteria.status
if search_criteria.target_ref_name is not None:
query_parameters['searchCriteria.targetRefName'] = search_criteria.target_ref_name
if search_criteria.source_repository_id is not None:
query_parameters['searchCriteria.sourceRepositoryId'] = search_criteria.source_repository_id
if search_criteria.source_ref_name is not None:
query_parameters['searchCriteria.sourceRefName'] = search_criteria.source_ref_name
if search_criteria.include_links is not None:
query_parameters['searchCriteria.includeLinks'] = search_criteria.include_links
if max_comment_length is not None:
query_parameters['maxCommentLength'] = self._serialize.query('max_comment_length', max_comment_length, 'int')
if skip is not None:
query_parameters['$skip'] = self._serialize.query('skip', skip, 'int')
if top is not None:
query_parameters['$top'] = self._serialize.query('top', top, 'int')
response = self._send(http_method='GET',
location_id='9946fd70-0d40-406e-b686-b4744cbbcc37',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('[GitPullRequest]', self._unwrap_collection(response))
def update_pull_request(self, git_pull_request_to_update, repository_id, pull_request_id, project=None):
"""UpdatePullRequest.
[Preview API] Update a pull request
:param :class:`<GitPullRequest> <azure.devops.v7_1.git.models.GitPullRequest>` git_pull_request_to_update: The pull request content that should be updated.
:param str repository_id: The repository ID of the pull request's target branch.
:param int pull_request_id: ID of the pull request to update.
:param str project: Project ID or project name
:rtype: :class:`<GitPullRequest> <azure.devops.v7_1.git.models.GitPullRequest>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
content = self._serialize.body(git_pull_request_to_update, 'GitPullRequest')
response = self._send(http_method='PATCH',
location_id='9946fd70-0d40-406e-b686-b4744cbbcc37',
version='7.1-preview.1',
route_values=route_values,
content=content)
return self._deserialize('GitPullRequest', response)
def share_pull_request(self, user_message, repository_id, pull_request_id, project=None):
"""SharePullRequest.
[Preview API] Sends an e-mail notification about a specific pull request to a set of recipients
:param :class:`<ShareNotificationContext> <azure.devops.v7_1.git.models.ShareNotificationContext>` user_message:
:param str repository_id: ID of the git repository.
:param int pull_request_id: ID of the pull request.
:param str project: Project ID or project name
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
content = self._serialize.body(user_message, 'ShareNotificationContext')
self._send(http_method='POST',
location_id='696f3a82-47c9-487f-9117-b9d00972ca84',
version='7.1-preview.1',
route_values=route_values,
content=content)
def create_pull_request_status(self, status, repository_id, pull_request_id, project=None):
"""CreatePullRequestStatus.
[Preview API] Create a pull request status.
:param :class:`<GitPullRequestStatus> <azure.devops.v7_1.git.models.GitPullRequestStatus>` status: Pull request status to create.
:param str repository_id: The repository ID of the pull request’s target branch.
:param int pull_request_id: ID of the pull request.
:param str project: Project ID or project name
:rtype: :class:`<GitPullRequestStatus> <azure.devops.v7_1.git.models.GitPullRequestStatus>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
content = self._serialize.body(status, 'GitPullRequestStatus')
response = self._send(http_method='POST',
location_id='b5f6bb4f-8d1e-4d79-8d11-4c9172c99c35',
version='7.1-preview.1',
route_values=route_values,
content=content)
return self._deserialize('GitPullRequestStatus', response)
def delete_pull_request_status(self, repository_id, pull_request_id, status_id, project=None):
"""DeletePullRequestStatus.
[Preview API] Delete pull request status.
:param str repository_id: The repository ID of the pull request’s target branch.
:param int pull_request_id: ID of the pull request.
:param int status_id: ID of the pull request status.
:param str project: Project ID or project name
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
if status_id is not None:
route_values['statusId'] = self._serialize.url('status_id', status_id, 'int')
self._send(http_method='DELETE',
location_id='b5f6bb4f-8d1e-4d79-8d11-4c9172c99c35',
version='7.1-preview.1',
route_values=route_values)
def get_pull_request_status(self, repository_id, pull_request_id, status_id, project=None):
"""GetPullRequestStatus.
[Preview API] Get the specific pull request status by ID. The status ID is unique within the pull request across all iterations.
:param str repository_id: The repository ID of the pull request’s target branch.
:param int pull_request_id: ID of the pull request.
:param int status_id: ID of the pull request status.
:param str project: Project ID or project name
:rtype: :class:`<GitPullRequestStatus> <azure.devops.v7_1.git.models.GitPullRequestStatus>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
if status_id is not None:
route_values['statusId'] = self._serialize.url('status_id', status_id, 'int')
response = self._send(http_method='GET',
location_id='b5f6bb4f-8d1e-4d79-8d11-4c9172c99c35',
version='7.1-preview.1',
route_values=route_values)
return self._deserialize('GitPullRequestStatus', response)
def get_pull_request_statuses(self, repository_id, pull_request_id, project=None):
"""GetPullRequestStatuses.
[Preview API] Get all the statuses associated with a pull request.
:param str repository_id: The repository ID of the pull request’s target branch.
:param int pull_request_id: ID of the pull request.
:param str project: Project ID or project name
:rtype: [GitPullRequestStatus]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
response = self._send(http_method='GET',
location_id='b5f6bb4f-8d1e-4d79-8d11-4c9172c99c35',
version='7.1-preview.1',
route_values=route_values)
return self._deserialize('[GitPullRequestStatus]', self._unwrap_collection(response))
def update_pull_request_statuses(self, patch_document, repository_id, pull_request_id, project=None):
"""UpdatePullRequestStatuses.
[Preview API] Update pull request statuses collection. The only supported operation type is `remove`.
:param :class:`<[JsonPatchOperation]> <azure.devops.v7_1.git.models.[JsonPatchOperation]>` patch_document: Operations to apply to the pull request statuses in JSON Patch format.
:param str repository_id: The repository ID of the pull request’s target branch.
:param int pull_request_id: ID of the pull request.
:param str project: Project ID or project name
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
content = self._serialize.body(patch_document, '[JsonPatchOperation]')
self._send(http_method='PATCH',
location_id='b5f6bb4f-8d1e-4d79-8d11-4c9172c99c35',
version='7.1-preview.1',
route_values=route_values,
content=content,
media_type='application/json-patch+json')
def create_comment(self, comment, repository_id, pull_request_id, thread_id, project=None):
"""CreateComment.
[Preview API] Create a comment on a specific thread in a pull request (up to 500 comments can be created per thread).
:param :class:`<Comment> <azure.devops.v7_1.git.models.Comment>` comment: The comment to create. Comments can be up to 150,000 characters.
:param str repository_id: The repository ID of the pull request's target branch.
:param int pull_request_id: ID of the pull request.
:param int thread_id: ID of the thread that the desired comment is in.
:param str project: Project ID or project name
:rtype: :class:`<Comment> <azure.devops.v7_1.git.models.Comment>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
if thread_id is not None:
route_values['threadId'] = self._serialize.url('thread_id', thread_id, 'int')
content = self._serialize.body(comment, 'Comment')
response = self._send(http_method='POST',
location_id='965a3ec7-5ed8-455a-bdcb-835a5ea7fe7b',
version='7.1-preview.1',
route_values=route_values,
content=content)
return self._deserialize('Comment', response)
def delete_comment(self, repository_id, pull_request_id, thread_id, comment_id, project=None):
"""DeleteComment.
[Preview API] Delete a comment associated with a specific thread in a pull request.
:param str repository_id: The repository ID of the pull request's target branch.
:param int pull_request_id: ID of the pull request.
:param int thread_id: ID of the thread that the desired comment is in.
:param int comment_id: ID of the comment.
:param str project: Project ID or project name
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
if thread_id is not None:
route_values['threadId'] = self._serialize.url('thread_id', thread_id, 'int')
if comment_id is not None:
route_values['commentId'] = self._serialize.url('comment_id', comment_id, 'int')
self._send(http_method='DELETE',
location_id='965a3ec7-5ed8-455a-bdcb-835a5ea7fe7b',
version='7.1-preview.1',
route_values=route_values)
def get_comment(self, repository_id, pull_request_id, thread_id, comment_id, project=None):
"""GetComment.
[Preview API] Retrieve a comment associated with a specific thread in a pull request.
:param str repository_id: The repository ID of the pull request's target branch.
:param int pull_request_id: ID of the pull request.
:param int thread_id: ID of the thread that the desired comment is in.
:param int comment_id: ID of the comment.
:param str project: Project ID or project name
:rtype: :class:`<Comment> <azure.devops.v7_1.git.models.Comment>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
if thread_id is not None:
route_values['threadId'] = self._serialize.url('thread_id', thread_id, 'int')
if comment_id is not None:
route_values['commentId'] = self._serialize.url('comment_id', comment_id, 'int')
response = self._send(http_method='GET',
location_id='965a3ec7-5ed8-455a-bdcb-835a5ea7fe7b',
version='7.1-preview.1',
route_values=route_values)
return self._deserialize('Comment', response)
def get_comments(self, repository_id, pull_request_id, thread_id, project=None):
"""GetComments.
[Preview API] Retrieve all comments associated with a specific thread in a pull request.
:param str repository_id: The repository ID of the pull request's target branch.
:param int pull_request_id: ID of the pull request.
:param int thread_id: ID of the thread.
:param str project: Project ID or project name
:rtype: [Comment]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
if thread_id is not None:
route_values['threadId'] = self._serialize.url('thread_id', thread_id, 'int')
response = self._send(http_method='GET',
location_id='965a3ec7-5ed8-455a-bdcb-835a5ea7fe7b',
version='7.1-preview.1',
route_values=route_values)
return self._deserialize('[Comment]', self._unwrap_collection(response))
def update_comment(self, comment, repository_id, pull_request_id, thread_id, comment_id, project=None):
"""UpdateComment.
[Preview API] Update a comment associated with a specific thread in a pull request.
:param :class:`<Comment> <azure.devops.v7_1.git.models.Comment>` comment: The comment content that should be updated. Comments can be up to 150,000 characters.
:param str repository_id: The repository ID of the pull request's target branch.
:param int pull_request_id: ID of the pull request.
:param int thread_id: ID of the thread that the desired comment is in.
:param int comment_id: ID of the comment to update.
:param str project: Project ID or project name
:rtype: :class:`<Comment> <azure.devops.v7_1.git.models.Comment>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
if thread_id is not None:
route_values['threadId'] = self._serialize.url('thread_id', thread_id, 'int')
if comment_id is not None:
route_values['commentId'] = self._serialize.url('comment_id', comment_id, 'int')
content = self._serialize.body(comment, 'Comment')
response = self._send(http_method='PATCH',
location_id='965a3ec7-5ed8-455a-bdcb-835a5ea7fe7b',
version='7.1-preview.1',
route_values=route_values,
content=content)
return self._deserialize('Comment', response)
def create_thread(self, comment_thread, repository_id, pull_request_id, project=None):
"""CreateThread.
[Preview API] Create a thread in a pull request.
:param :class:`<GitPullRequestCommentThread> <azure.devops.v7_1.git.models.GitPullRequestCommentThread>` comment_thread: The thread to create. Thread must contain at least one comment.
:param str repository_id: Repository ID of the pull request's target branch.
:param int pull_request_id: ID of the pull request.
:param str project: Project ID or project name
:rtype: :class:`<GitPullRequestCommentThread> <azure.devops.v7_1.git.models.GitPullRequestCommentThread>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
content = self._serialize.body(comment_thread, 'GitPullRequestCommentThread')
response = self._send(http_method='POST',
location_id='ab6e2e5d-a0b7-4153-b64a-a4efe0d49449',
version='7.1-preview.1',
route_values=route_values,
content=content)
return self._deserialize('GitPullRequestCommentThread', response)
def get_pull_request_thread(self, repository_id, pull_request_id, thread_id, project=None, iteration=None, base_iteration=None):
"""GetPullRequestThread.
[Preview API] Retrieve a thread in a pull request.
:param str repository_id: The repository ID of the pull request's target branch.
:param int pull_request_id: ID of the pull request.
:param int thread_id: ID of the thread.
:param str project: Project ID or project name
:param int iteration: If specified, thread position will be tracked using this iteration as the right side of the diff.
:param int base_iteration: If specified, thread position will be tracked using this iteration as the left side of the diff.
:rtype: :class:`<GitPullRequestCommentThread> <azure.devops.v7_1.git.models.GitPullRequestCommentThread>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
if thread_id is not None:
route_values['threadId'] = self._serialize.url('thread_id', thread_id, 'int')
query_parameters = {}
if iteration is not None:
query_parameters['$iteration'] = self._serialize.query('iteration', iteration, 'int')
if base_iteration is not None:
query_parameters['$baseIteration'] = self._serialize.query('base_iteration', base_iteration, 'int')
response = self._send(http_method='GET',
location_id='ab6e2e5d-a0b7-4153-b64a-a4efe0d49449',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('GitPullRequestCommentThread', response)
def get_threads(self, repository_id, pull_request_id, project=None, iteration=None, base_iteration=None):
"""GetThreads.
[Preview API] Retrieve all threads in a pull request.
:param str repository_id: The repository ID of the pull request's target branch.
:param int pull_request_id: ID of the pull request.
:param str project: Project ID or project name
:param int iteration: If specified, thread positions will be tracked using this iteration as the right side of the diff.
:param int base_iteration: If specified, thread positions will be tracked using this iteration as the left side of the diff.
:rtype: [GitPullRequestCommentThread]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
query_parameters = {}
if iteration is not None:
query_parameters['$iteration'] = self._serialize.query('iteration', iteration, 'int')
if base_iteration is not None:
query_parameters['$baseIteration'] = self._serialize.query('base_iteration', base_iteration, 'int')
response = self._send(http_method='GET',
location_id='ab6e2e5d-a0b7-4153-b64a-a4efe0d49449',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('[GitPullRequestCommentThread]', self._unwrap_collection(response))
def update_thread(self, comment_thread, repository_id, pull_request_id, thread_id, project=None):
"""UpdateThread.
[Preview API] Update a thread in a pull request.
:param :class:`<GitPullRequestCommentThread> <azure.devops.v7_1.git.models.GitPullRequestCommentThread>` comment_thread: The thread content that should be updated.
:param str repository_id: The repository ID of the pull request's target branch.
:param int pull_request_id: ID of the pull request.
:param int thread_id: ID of the thread to update.
:param str project: Project ID or project name
:rtype: :class:`<GitPullRequestCommentThread> <azure.devops.v7_1.git.models.GitPullRequestCommentThread>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
if thread_id is not None:
route_values['threadId'] = self._serialize.url('thread_id', thread_id, 'int')
content = self._serialize.body(comment_thread, 'GitPullRequestCommentThread')
response = self._send(http_method='PATCH',
location_id='ab6e2e5d-a0b7-4153-b64a-a4efe0d49449',
version='7.1-preview.1',
route_values=route_values,
content=content)
return self._deserialize('GitPullRequestCommentThread', response)
def get_pull_request_work_item_refs(self, repository_id, pull_request_id, project=None):
"""GetPullRequestWorkItemRefs.
[Preview API] Retrieve a list of work items associated with a pull request.
:param str repository_id: ID or name of the repository.
:param int pull_request_id: ID of the pull request.
:param str project: Project ID or project name
:rtype: [ResourceRef]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
response = self._send(http_method='GET',
location_id='0a637fcc-5370-4ce8-b0e8-98091f5f9482',
version='7.1-preview.1',
route_values=route_values)
return self._deserialize('[ResourceRef]', self._unwrap_collection(response))
def create_push(self, push, repository_id, project=None):
"""CreatePush.
[Preview API] Push changes to the repository.
:param :class:`<GitPush> <azure.devops.v7_1.git.models.GitPush>` push:
:param str repository_id: The name or ID of the repository.
:param str project: Project ID or project name
:rtype: :class:`<GitPush> <azure.devops.v7_1.git.models.GitPush>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
content = self._serialize.body(push, 'GitPush')
response = self._send(http_method='POST',
location_id='ea98d07b-3c87-4971-8ede-a613694ffb55',
version='7.1-preview.2',
route_values=route_values,
content=content)
return self._deserialize('GitPush', response)
def get_push(self, repository_id, push_id, project=None, include_commits=None, include_ref_updates=None):
"""GetPush.
[Preview API] Retrieves a particular push.
:param str repository_id: The name or ID of the repository.
:param int push_id: ID of the push.
:param str project: Project ID or project name
:param int include_commits: The number of commits to include in the result.
:param bool include_ref_updates: If true, include the list of refs that were updated by the push.
:rtype: :class:`<GitPush> <azure.devops.v7_1.git.models.GitPush>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if push_id is not None:
route_values['pushId'] = self._serialize.url('push_id', push_id, 'int')
query_parameters = {}
if include_commits is not None:
query_parameters['includeCommits'] = self._serialize.query('include_commits', include_commits, 'int')
if include_ref_updates is not None:
query_parameters['includeRefUpdates'] = self._serialize.query('include_ref_updates', include_ref_updates, 'bool')
response = self._send(http_method='GET',
location_id='ea98d07b-3c87-4971-8ede-a613694ffb55',
version='7.1-preview.2',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('GitPush', response)
def get_pushes(self, repository_id, project=None, skip=None, top=None, search_criteria=None):
"""GetPushes.
[Preview API] Retrieves pushes associated with the specified repository.
:param str repository_id: The name or ID of the repository.
:param str project: Project ID or project name
:param int skip: Number of pushes to skip.
:param int top: Number of pushes to return.
:param :class:`<GitPushSearchCriteria> <azure.devops.v7_1.git.models.GitPushSearchCriteria>` search_criteria: Search criteria attributes: fromDate, toDate, pusherId, refName, includeRefUpdates or includeLinks. fromDate: Start date to search from. toDate: End date to search to. pusherId: Identity of the person who submitted the push. refName: Branch name to consider. includeRefUpdates: If true, include the list of refs that were updated by the push. includeLinks: Whether to include the _links field on the shallow references.
:rtype: [GitPush]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
query_parameters = {}
if skip is not None:
query_parameters['$skip'] = self._serialize.query('skip', skip, 'int')
if top is not None:
query_parameters['$top'] = self._serialize.query('top', top, 'int')
if search_criteria is not None:
if search_criteria.from_date is not None:
query_parameters['searchCriteria.fromDate'] = search_criteria.from_date
if search_criteria.to_date is not None:
query_parameters['searchCriteria.toDate'] = search_criteria.to_date
if search_criteria.pusher_id is not None:
query_parameters['searchCriteria.pusherId'] = search_criteria.pusher_id
if search_criteria.ref_name is not None:
query_parameters['searchCriteria.refName'] = search_criteria.ref_name
if search_criteria.include_ref_updates is not None:
query_parameters['searchCriteria.includeRefUpdates'] = search_criteria.include_ref_updates
if search_criteria.include_links is not None:
query_parameters['searchCriteria.includeLinks'] = search_criteria.include_links
response = self._send(http_method='GET',
location_id='ea98d07b-3c87-4971-8ede-a613694ffb55',
version='7.1-preview.2',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('[GitPush]', self._unwrap_collection(response))
def delete_repository_from_recycle_bin(self, project, repository_id):
"""DeleteRepositoryFromRecycleBin.
[Preview API] Destroy (hard delete) a soft-deleted Git repository.
:param str project: Project ID or project name
:param str repository_id: The ID of the repository.
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
self._send(http_method='DELETE',
location_id='a663da97-81db-4eb3-8b83-287670f63073',
version='7.1-preview.1',
route_values=route_values)
def get_recycle_bin_repositories(self, project):
"""GetRecycleBinRepositories.
[Preview API] Retrieve soft-deleted git repositories from the recycle bin.
:param str project: Project ID or project name
:rtype: [GitDeletedRepository]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
response = self._send(http_method='GET',
location_id='a663da97-81db-4eb3-8b83-287670f63073',
version='7.1-preview.1',
route_values=route_values)
return self._deserialize('[GitDeletedRepository]', self._unwrap_collection(response))
def restore_repository_from_recycle_bin(self, repository_details, project, repository_id):
"""RestoreRepositoryFromRecycleBin.
[Preview API] Recover a soft-deleted Git repository. Recently deleted repositories go into a soft-delete state for a period of time before they are hard deleted and become unrecoverable.
:param :class:`<GitRecycleBinRepositoryDetails> <azure.devops.v7_1.git.models.GitRecycleBinRepositoryDetails>` repository_details:
:param str project: Project ID or project name
:param str repository_id: The ID of the repository.
:rtype: :class:`<GitRepository> <azure.devops.v7_1.git.models.GitRepository>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
content = self._serialize.body(repository_details, 'GitRecycleBinRepositoryDetails')
response = self._send(http_method='PATCH',
location_id='a663da97-81db-4eb3-8b83-287670f63073',
version='7.1-preview.1',
route_values=route_values,
content=content)
return self._deserialize('GitRepository', response)
def get_refs(self, repository_id, project=None, filter=None, include_links=None, include_statuses=None, include_my_branches=None, latest_statuses_only=None, peel_tags=None, filter_contains=None, top=None, continuation_token=None):
"""GetRefs.
[Preview API] Queries the provided repository for its refs and returns them.
:param str repository_id: The name or ID of the repository.
:param str project: Project ID or project name
:param str filter: [optional] A filter to apply to the refs (starts with).
:param bool include_links: [optional] Specifies if referenceLinks should be included in the result. default is false.
:param bool include_statuses: [optional] Includes up to the first 1000 commit statuses for each ref. The default value is false.
:param bool include_my_branches: [optional] Includes only branches that the user owns, the branches the user favorites, and the default branch. The default value is false. Cannot be combined with the filter parameter.
:param bool latest_statuses_only: [optional] True to include only the tip commit status for each ref. This option requires `includeStatuses` to be true. The default value is false.
:param bool peel_tags: [optional] Annotated tags will populate the PeeledObjectId property. default is false.
:param str filter_contains: [optional] A filter to apply to the refs (contains).
:param int top: [optional] Maximum number of refs to return. It cannot be bigger than 1000. If it is not provided but continuationToken is, top will default to 100.
:param str continuation_token: The continuation token used for pagination.
:rtype: :class:`<[GitRef]> <azure.devops.v7_1.git.models.[GitRef]>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query('filter', filter, 'str')
if include_links is not None:
query_parameters['includeLinks'] = self._serialize.query('include_links', include_links, 'bool')
if include_statuses is not None:
query_parameters['includeStatuses'] = self._serialize.query('include_statuses', include_statuses, 'bool')
if include_my_branches is not None:
query_parameters['includeMyBranches'] = self._serialize.query('include_my_branches', include_my_branches, 'bool')
if latest_statuses_only is not None:
query_parameters['latestStatusesOnly'] = self._serialize.query('latest_statuses_only', latest_statuses_only, 'bool')
if peel_tags is not None:
query_parameters['peelTags'] = self._serialize.query('peel_tags', peel_tags, 'bool')
if filter_contains is not None:
query_parameters['filterContains'] = self._serialize.query('filter_contains', filter_contains, 'str')
if top is not None:
query_parameters['$top'] = self._serialize.query('top', top, 'int')
if continuation_token is not None:
query_parameters['continuationToken'] = self._serialize.query('continuation_token', continuation_token, 'str')
response = self._send(http_method='GET',
location_id='2d874a60-a811-4f62-9c9f-963a6ea0a55b',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('[GitRef]', self._unwrap_collection(response))
def update_ref(self, new_ref_info, repository_id, filter, project=None, project_id=None):
"""UpdateRef.
[Preview API] Lock or Unlock a branch.
:param :class:`<GitRefUpdate> <azure.devops.v7_1.git.models.GitRefUpdate>` new_ref_info: The ref update action (lock/unlock) to perform
:param str repository_id: The name or ID of the repository.
:param str filter: The name of the branch to lock/unlock
:param str project: Project ID or project name
:param str project_id: ID or name of the team project. Optional if specifying an ID for repository.
:rtype: :class:`<GitRef> <azure.devops.v7_1.git.models.GitRef>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query('filter', filter, 'str')
if project_id is not None:
query_parameters['projectId'] = self._serialize.query('project_id', project_id, 'str')
content = self._serialize.body(new_ref_info, 'GitRefUpdate')
response = self._send(http_method='PATCH',
location_id='2d874a60-a811-4f62-9c9f-963a6ea0a55b',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters,
content=content)
return self._deserialize('GitRef', response)
def update_refs(self, ref_updates, repository_id, project=None, project_id=None):
"""UpdateRefs.
[Preview API] Creating, updating, or deleting refs(branches).
:param [GitRefUpdate] ref_updates: List of ref updates to attempt to perform
:param str repository_id: The name or ID of the repository.
:param str project: Project ID or project name
:param str project_id: ID or name of the team project. Optional if specifying an ID for repository.
:rtype: [GitRefUpdateResult]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
query_parameters = {}
if project_id is not None:
query_parameters['projectId'] = self._serialize.query('project_id', project_id, 'str')
content = self._serialize.body(ref_updates, '[GitRefUpdate]')
response = self._send(http_method='POST',
location_id='2d874a60-a811-4f62-9c9f-963a6ea0a55b',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters,
content=content)
return self._deserialize('[GitRefUpdateResult]', self._unwrap_collection(response))
def create_favorite(self, favorite, project):
"""CreateFavorite.
[Preview API] Creates a ref favorite
:param :class:`<GitRefFavorite> <azure.devops.v7_1.git.models.GitRefFavorite>` favorite: The ref favorite to create.
:param str project: Project ID or project name
:rtype: :class:`<GitRefFavorite> <azure.devops.v7_1.git.models.GitRefFavorite>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
content = self._serialize.body(favorite, 'GitRefFavorite')
response = self._send(http_method='POST',
location_id='876f70af-5792-485a-a1c7-d0a7b2f42bbb',
version='7.1-preview.1',
route_values=route_values,
content=content)
return self._deserialize('GitRefFavorite', response)
def delete_ref_favorite(self, project, favorite_id):
"""DeleteRefFavorite.
[Preview API] Deletes the refs favorite specified
:param str project: Project ID or project name
:param int favorite_id: The Id of the ref favorite to delete.
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if favorite_id is not None:
route_values['favoriteId'] = self._serialize.url('favorite_id', favorite_id, 'int')
self._send(http_method='DELETE',
location_id='876f70af-5792-485a-a1c7-d0a7b2f42bbb',
version='7.1-preview.1',
route_values=route_values)
def get_ref_favorite(self, project, favorite_id):
"""GetRefFavorite.
[Preview API] Gets the refs favorite for a favorite Id.
:param str project: Project ID or project name
:param int favorite_id: The Id of the requested ref favorite.
:rtype: :class:`<GitRefFavorite> <azure.devops.v7_1.git.models.GitRefFavorite>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if favorite_id is not None:
route_values['favoriteId'] = self._serialize.url('favorite_id', favorite_id, 'int')
response = self._send(http_method='GET',
location_id='876f70af-5792-485a-a1c7-d0a7b2f42bbb',
version='7.1-preview.1',
route_values=route_values)
return self._deserialize('GitRefFavorite', response)
def get_ref_favorites(self, project, repository_id=None, identity_id=None):
"""GetRefFavorites.
[Preview API] Gets the refs favorites for a repo and an identity.
:param str project: Project ID or project name
:param str repository_id: The id of the repository.
:param str identity_id: The id of the identity whose favorites are to be retrieved. If null, the requesting identity is used.
:rtype: [GitRefFavorite]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
query_parameters = {}
if repository_id is not None:
query_parameters['repositoryId'] = self._serialize.query('repository_id', repository_id, 'str')
if identity_id is not None:
query_parameters['identityId'] = self._serialize.query('identity_id', identity_id, 'str')
response = self._send(http_method='GET',
location_id='876f70af-5792-485a-a1c7-d0a7b2f42bbb',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('[GitRefFavorite]', self._unwrap_collection(response))
def create_repository(self, git_repository_to_create, project=None, source_ref=None):
"""CreateRepository.
[Preview API] Create a git repository in a team project.
:param :class:`<GitRepositoryCreateOptions> <azure.devops.v7_1.git.models.GitRepositoryCreateOptions>` git_repository_to_create: Specify the repo name, team project and/or parent repository. Team project information can be omitted from gitRepositoryToCreate if the request is project-scoped (i.e., includes project Id).
:param str project: Project ID or project name
:param str source_ref: [optional] Specify the source refs to use while creating a fork repo
:rtype: :class:`<GitRepository> <azure.devops.v7_1.git.models.GitRepository>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
query_parameters = {}
if source_ref is not None:
query_parameters['sourceRef'] = self._serialize.query('source_ref', source_ref, 'str')
content = self._serialize.body(git_repository_to_create, 'GitRepositoryCreateOptions')
response = self._send(http_method='POST',
location_id='225f7195-f9c7-4d14-ab28-a83f7ff77e1f',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters,
content=content)
return self._deserialize('GitRepository', response)
def delete_repository(self, repository_id, project=None):
"""DeleteRepository.
[Preview API] Delete a git repository
:param str repository_id: The ID of the repository.
:param str project: Project ID or project name
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
self._send(http_method='DELETE',
location_id='225f7195-f9c7-4d14-ab28-a83f7ff77e1f',
version='7.1-preview.1',
route_values=route_values)
def get_repositories(self, project=None, include_links=None, include_all_urls=None, include_hidden=None):
"""GetRepositories.
[Preview API] Retrieve git repositories.
:param str project: Project ID or project name
:param bool include_links: [optional] True to include reference links. The default value is false.
:param bool include_all_urls: [optional] True to include all remote URLs. The default value is false.
:param bool include_hidden: [optional] True to include hidden repositories. The default value is false.
:rtype: [GitRepository]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
query_parameters = {}
if include_links is not None:
query_parameters['includeLinks'] = self._serialize.query('include_links', include_links, 'bool')
if include_all_urls is not None:
query_parameters['includeAllUrls'] = self._serialize.query('include_all_urls', include_all_urls, 'bool')
if include_hidden is not None:
query_parameters['includeHidden'] = self._serialize.query('include_hidden', include_hidden, 'bool')
response = self._send(http_method='GET',
location_id='225f7195-f9c7-4d14-ab28-a83f7ff77e1f',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('[GitRepository]', self._unwrap_collection(response))
def get_repository(self, repository_id, project=None):
"""GetRepository.
[Preview API] Retrieve a git repository.
:param str repository_id: The name or ID of the repository.
:param str project: Project ID or project name
:rtype: :class:`<GitRepository> <azure.devops.v7_1.git.models.GitRepository>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
response = self._send(http_method='GET',
location_id='225f7195-f9c7-4d14-ab28-a83f7ff77e1f',
version='7.1-preview.1',
route_values=route_values)
return self._deserialize('GitRepository', response)
def get_repository_with_parent(self, repository_id, include_parent, project=None):
"""GetRepositoryWithParent.
[Preview API] Retrieve a git repository.
:param str repository_id: The name or ID of the repository.
:param bool include_parent: True to include parent repository. Only available in authenticated calls.
:param str project: Project ID or project name
:rtype: :class:`<GitRepository> <azure.devops.v7_1.git.models.GitRepository>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
query_parameters = {}
if include_parent is not None:
query_parameters['includeParent'] = self._serialize.query('include_parent', include_parent, 'bool')
response = self._send(http_method='GET',
location_id='225f7195-f9c7-4d14-ab28-a83f7ff77e1f',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('GitRepository', response)
def update_repository(self, new_repository_info, repository_id, project=None):
"""UpdateRepository.
[Preview API] Updates the Git repository with either a new repo name or a new default branch.
:param :class:`<GitRepository> <azure.devops.v7_1.git.models.GitRepository>` new_repository_info: Specify a new repo name or a new default branch of the repository
:param str repository_id: The ID of the repository.
:param str project: Project ID or project name
:rtype: :class:`<GitRepository> <azure.devops.v7_1.git.models.GitRepository>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
content = self._serialize.body(new_repository_info, 'GitRepository')
response = self._send(http_method='PATCH',
location_id='225f7195-f9c7-4d14-ab28-a83f7ff77e1f',
version='7.1-preview.1',
route_values=route_values,
content=content)
return self._deserialize('GitRepository', response)
def get_stats(self, project, repository_id):
"""GetStats.
[Preview API] Retrieves statistics of a repository.
:param str project: Project ID or project name
:param str repository_id: Friendly name or guid of repository.
:rtype: :class:`<GitRepositoryStats> <azure.devops.v7_1.git.models.GitRepositoryStats>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
response = self._send(http_method='GET',
location_id='616a5255-74b3-40f5-ae1d-bbae2eec8db5',
version='7.1-preview.1',
route_values=route_values)
return self._deserialize('GitRepositoryStats', response)
def create_revert(self, revert_to_create, project, repository_id):
"""CreateRevert.
[Preview API] Starts the operation to create a new branch which reverts changes introduced by either a specific commit or commits that are associated to a pull request.
:param :class:`<GitAsyncRefOperationParameters> <azure.devops.v7_1.git.models.GitAsyncRefOperationParameters>` revert_to_create:
:param str project: Project ID or project name
:param str repository_id: ID of the repository.
:rtype: :class:`<GitRevert> <azure.devops.v7_1.git.models.GitRevert>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
content = self._serialize.body(revert_to_create, 'GitAsyncRefOperationParameters')
response = self._send(http_method='POST',
location_id='bc866058-5449-4715-9cf1-a510b6ff193c',
version='7.1-preview.1',
route_values=route_values,
content=content)
return self._deserialize('GitRevert', response)
def get_revert(self, project, revert_id, repository_id):
"""GetRevert.
[Preview API] Retrieve information about a revert operation by revert Id.
:param str project: Project ID or project name
:param int revert_id: ID of the revert operation.
:param str repository_id: ID of the repository.
:rtype: :class:`<GitRevert> <azure.devops.v7_1.git.models.GitRevert>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if revert_id is not None:
route_values['revertId'] = self._serialize.url('revert_id', revert_id, 'int')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
response = self._send(http_method='GET',
location_id='bc866058-5449-4715-9cf1-a510b6ff193c',
version='7.1-preview.1',
route_values=route_values)
return self._deserialize('GitRevert', response)
def get_revert_for_ref_name(self, project, repository_id, ref_name):
"""GetRevertForRefName.
[Preview API] Retrieve information about a revert operation for a specific branch.
:param str project: Project ID or project name
:param str repository_id: ID of the repository.
:param str ref_name: The GitAsyncRefOperationParameters generatedRefName used for the revert operation.
:rtype: :class:`<GitRevert> <azure.devops.v7_1.git.models.GitRevert>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
query_parameters = {}
if ref_name is not None:
query_parameters['refName'] = self._serialize.query('ref_name', ref_name, 'str')
response = self._send(http_method='GET',
location_id='bc866058-5449-4715-9cf1-a510b6ff193c',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('GitRevert', response)
def create_commit_status(self, git_commit_status_to_create, commit_id, repository_id, project=None):
"""CreateCommitStatus.
[Preview API] Create Git commit status.
:param :class:`<GitStatus> <azure.devops.v7_1.git.models.GitStatus>` git_commit_status_to_create: Git commit status object to create.
:param str commit_id: ID of the Git commit.
:param str repository_id: ID of the repository.
:param str project: Project ID or project name
:rtype: :class:`<GitStatus> <azure.devops.v7_1.git.models.GitStatus>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if commit_id is not None:
route_values['commitId'] = self._serialize.url('commit_id', commit_id, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
content = self._serialize.body(git_commit_status_to_create, 'GitStatus')
response = self._send(http_method='POST',
location_id='428dd4fb-fda5-4722-af02-9313b80305da',
version='7.1-preview.1',
route_values=route_values,
content=content)
return self._deserialize('GitStatus', response)
def get_statuses(self, commit_id, repository_id, project=None, top=None, skip=None, latest_only=None):
"""GetStatuses.
[Preview API] Get statuses associated with the Git commit.
:param str commit_id: ID of the Git commit.
:param str repository_id: ID of the repository.
:param str project: Project ID or project name
:param int top: Optional. The number of statuses to retrieve. Default is 1000.
:param int skip: Optional. The number of statuses to ignore. Default is 0. For example, to retrieve results 101-150, set top to 50 and skip to 100.
:param bool latest_only: The flag indicates whether to get only latest statuses grouped by `Context.Name` and `Context.Genre`.
:rtype: [GitStatus]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if commit_id is not None:
route_values['commitId'] = self._serialize.url('commit_id', commit_id, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
query_parameters = {}
if top is not None:
query_parameters['top'] = self._serialize.query('top', top, 'int')
if skip is not None:
query_parameters['skip'] = self._serialize.query('skip', skip, 'int')
if latest_only is not None:
query_parameters['latestOnly'] = self._serialize.query('latest_only', latest_only, 'bool')
response = self._send(http_method='GET',
location_id='428dd4fb-fda5-4722-af02-9313b80305da',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('[GitStatus]', self._unwrap_collection(response))
def get_suggestions(self, repository_id, project=None):
"""GetSuggestions.
[Preview API] Retrieve a pull request suggestion for a particular repository or team project.
:param str repository_id: ID of the git repository.
:param str project: Project ID or project name
:rtype: [GitSuggestion]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
response = self._send(http_method='GET',
location_id='9393b4fb-4445-4919-972b-9ad16f442d83',
version='7.1-preview.1',
route_values=route_values)
return self._deserialize('[GitSuggestion]', self._unwrap_collection(response))
def get_tree(self, repository_id, sha1, project=None, project_id=None, recursive=None, file_name=None):
"""GetTree.
[Preview API] The Tree endpoint returns the collection of objects underneath the specified tree. Trees are folders in a Git repository.
:param str repository_id: Repository Id.
:param str sha1: SHA1 hash of the tree object.
:param str project: Project ID or project name
:param str project_id: Project Id.
:param bool recursive: Search recursively. Include trees underneath this tree. Default is false.
:param str file_name: Name to use if a .zip file is returned. Default is the object ID.
:rtype: :class:`<GitTreeRef> <azure.devops.v7_1.git.models.GitTreeRef>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if sha1 is not None:
route_values['sha1'] = self._serialize.url('sha1', sha1, 'str')
query_parameters = {}
if project_id is not None:
query_parameters['projectId'] = self._serialize.query('project_id', project_id, 'str')
if recursive is not None:
query_parameters['recursive'] = self._serialize.query('recursive', recursive, 'bool')
if file_name is not None:
query_parameters['fileName'] = self._serialize.query('file_name', file_name, 'str')
response = self._send(http_method='GET',
location_id='729f6437-6f92-44ec-8bee-273a7111063c',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('GitTreeRef', response)
def get_tree_zip(self, repository_id, sha1, project=None, project_id=None, recursive=None, file_name=None, **kwargs):
"""GetTreeZip.
[Preview API] The Tree endpoint returns the collection of objects underneath the specified tree. Trees are folders in a Git repository.
:param str repository_id: Repository Id.
:param str sha1: SHA1 hash of the tree object.
:param str project: Project ID or project name
:param str project_id: Project Id.
:param bool recursive: Search recursively. Include trees underneath this tree. Default is false.
:param str file_name: Name to use if a .zip file is returned. Default is the object ID.
:rtype: object
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if sha1 is not None:
route_values['sha1'] = self._serialize.url('sha1', sha1, 'str')
query_parameters = {}
if project_id is not None:
query_parameters['projectId'] = self._serialize.query('project_id', project_id, 'str')
if recursive is not None:
query_parameters['recursive'] = self._serialize.query('recursive', recursive, 'bool')
if file_name is not None:
query_parameters['fileName'] = self._serialize.query('file_name', file_name, 'str')
response = self._send(http_method='GET',
location_id='729f6437-6f92-44ec-8bee-273a7111063c',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters,
accept_media_type='application/zip')
if "callback" in kwargs:
callback = kwargs["callback"]
else:
callback = None
return self._client.stream_download(response, callback=callback)
|
azure-devops-python-api/azure-devops/azure/devops/v7_1/git/git_client_base.py/0
|
{
"file_path": "azure-devops-python-api/azure-devops/azure/devops/v7_1/git/git_client_base.py",
"repo_id": "azure-devops-python-api",
"token_count": 90188
}
| 363 |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
# Generated file, DO NOT EDIT
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------------------------
from msrest.serialization import Model
class AccessLevel(Model):
"""
License assigned to a user
:param account_license_type: Type of Account License (e.g. Express, Stakeholder etc.)
:type account_license_type: object
:param assignment_source: Assignment Source of the License (e.g. Group, Unknown etc.
:type assignment_source: object
:param license_display_name: Display name of the License
:type license_display_name: str
:param licensing_source: Licensing Source (e.g. Account. MSDN etc.)
:type licensing_source: object
:param msdn_license_type: Type of MSDN License (e.g. Visual Studio Professional, Visual Studio Enterprise etc.)
:type msdn_license_type: object
:param status: User status in the account
:type status: object
:param status_message: Status message.
:type status_message: str
"""
_attribute_map = {
'account_license_type': {'key': 'accountLicenseType', 'type': 'object'},
'assignment_source': {'key': 'assignmentSource', 'type': 'object'},
'license_display_name': {'key': 'licenseDisplayName', 'type': 'str'},
'licensing_source': {'key': 'licensingSource', 'type': 'object'},
'msdn_license_type': {'key': 'msdnLicenseType', 'type': 'object'},
'status': {'key': 'status', 'type': 'object'},
'status_message': {'key': 'statusMessage', 'type': 'str'}
}
def __init__(self, account_license_type=None, assignment_source=None, license_display_name=None, licensing_source=None, msdn_license_type=None, status=None, status_message=None):
super(AccessLevel, self).__init__()
self.account_license_type = account_license_type
self.assignment_source = assignment_source
self.license_display_name = license_display_name
self.licensing_source = licensing_source
self.msdn_license_type = msdn_license_type
self.status = status
self.status_message = status_message
class BaseOperationResult(Model):
"""
:param errors: List of error codes paired with their corresponding error messages
:type errors: list of { key: int; value: str }
:param is_success: Success status of the operation
:type is_success: bool
"""
_attribute_map = {
'errors': {'key': 'errors', 'type': '[{ key: int; value: str }]'},
'is_success': {'key': 'isSuccess', 'type': 'bool'}
}
def __init__(self, errors=None, is_success=None):
super(BaseOperationResult, self).__init__()
self.errors = errors
self.is_success = is_success
class EntitlementBase(Model):
"""
:param access_level: Member's access level denoted by a license.
:type access_level: :class:`AccessLevel <azure.devops.v7_1.member_entitlement_management.models.AccessLevel>`
:param date_created: [Readonly] Date the member was added to the collection.
:type date_created: datetime
:param group_assignments: [Readonly] GroupEntitlements that this member belongs to.
:type group_assignments: list of :class:`GroupEntitlement <azure.devops.v7_1.member_entitlement_management.models.GroupEntitlement>`
:param id: The unique identifier which matches the Id of the Identity associated with the GraphMember.
:type id: str
:param last_accessed_date: [Readonly] Date the member last accessed the collection.
:type last_accessed_date: datetime
:param project_entitlements: Relation between a project and the member's effective permissions in that project.
:type project_entitlements: list of :class:`ProjectEntitlement <azure.devops.v7_1.member_entitlement_management.models.ProjectEntitlement>`
"""
_attribute_map = {
'access_level': {'key': 'accessLevel', 'type': 'AccessLevel'},
'date_created': {'key': 'dateCreated', 'type': 'iso-8601'},
'group_assignments': {'key': 'groupAssignments', 'type': '[GroupEntitlement]'},
'id': {'key': 'id', 'type': 'str'},
'last_accessed_date': {'key': 'lastAccessedDate', 'type': 'iso-8601'},
'project_entitlements': {'key': 'projectEntitlements', 'type': '[ProjectEntitlement]'}
}
def __init__(self, access_level=None, date_created=None, group_assignments=None, id=None, last_accessed_date=None, project_entitlements=None):
super(EntitlementBase, self).__init__()
self.access_level = access_level
self.date_created = date_created
self.group_assignments = group_assignments
self.id = id
self.last_accessed_date = last_accessed_date
self.project_entitlements = project_entitlements
class EntitlementOperationResultBase(Model):
"""
:param errors: List of error codes paired with their corresponding error messages.
:type errors: list of { key: int; value: str }
:param is_success: Success status of the operation.
:type is_success: bool
:param result: Resulting entitlement property. For specific implementations, see also: <seealso cref="T:Microsoft.VisualStudio.Services.MemberEntitlementManagement.WebApi.ServicePrincipalEntitlementOperationResult" /><seealso cref="T:Microsoft.VisualStudio.Services.MemberEntitlementManagement.WebApi.UserEntitlementOperationResult" />
:type result: object
"""
_attribute_map = {
'errors': {'key': 'errors', 'type': '[{ key: int; value: str }]'},
'is_success': {'key': 'isSuccess', 'type': 'bool'},
'result': {'key': 'result', 'type': 'object'}
}
def __init__(self, errors=None, is_success=None, result=None):
super(EntitlementOperationResultBase, self).__init__()
self.errors = errors
self.is_success = is_success
self.result = result
class Extension(Model):
"""
An extension assigned to a user
:param assignment_source: Assignment source for this extension. I.e. explicitly assigned or from a group rule.
:type assignment_source: object
:param id: Gallery Id of the Extension.
:type id: str
:param name: Friendly name of this extension.
:type name: str
:param source: Source of this extension assignment. Ex: msdn, account, none, etc.
:type source: object
"""
_attribute_map = {
'assignment_source': {'key': 'assignmentSource', 'type': 'object'},
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'source': {'key': 'source', 'type': 'object'}
}
def __init__(self, assignment_source=None, id=None, name=None, source=None):
super(Extension, self).__init__()
self.assignment_source = assignment_source
self.id = id
self.name = name
self.source = source
class GraphSubjectBase(Model):
"""
:param _links: This field contains zero or more interesting links about the graph subject. These links may be invoked to obtain additional relationships or more detailed information about this graph subject.
:type _links: :class:`ReferenceLinks <azure.devops.v7_1.microsoft._visual_studio._services._web_api.models.ReferenceLinks>`
:param descriptor: The descriptor is the primary way to reference the graph subject while the system is running. This field will uniquely identify the same graph subject across both Accounts and Organizations.
:type descriptor: str
:param display_name: This is the non-unique display name of the graph subject. To change this field, you must alter its value in the source provider.
:type display_name: str
:param url: This url is the full route to the source resource of this graph subject.
:type url: str
"""
_attribute_map = {
'_links': {'key': '_links', 'type': 'ReferenceLinks'},
'descriptor': {'key': 'descriptor', 'type': 'str'},
'display_name': {'key': 'displayName', 'type': 'str'},
'url': {'key': 'url', 'type': 'str'}
}
def __init__(self, _links=None, descriptor=None, display_name=None, url=None):
super(GraphSubjectBase, self).__init__()
self._links = _links
self.descriptor = descriptor
self.display_name = display_name
self.url = url
class Group(Model):
"""
Project Group (e.g. Contributor, Reader etc.)
:param display_name: Display Name of the Group
:type display_name: str
:param group_type: Group Type
:type group_type: object
"""
_attribute_map = {
'display_name': {'key': 'displayName', 'type': 'str'},
'group_type': {'key': 'groupType', 'type': 'object'}
}
def __init__(self, display_name=None, group_type=None):
super(Group, self).__init__()
self.display_name = display_name
self.group_type = group_type
class GroupEntitlement(Model):
"""
A group entity with additional properties including its license, extensions, and project membership
:param extension_rules: Extension Rules.
:type extension_rules: list of :class:`Extension <azure.devops.v7_1.member_entitlement_management.models.Extension>`
:param group: Member reference.
:type group: :class:`GraphGroup <azure.devops.v7_1.member_entitlement_management.models.GraphGroup>`
:param id: The unique identifier which matches the Id of the GraphMember.
:type id: str
:param last_executed: [Readonly] The last time the group licensing rule was executed (regardless of whether any changes were made).
:type last_executed: datetime
:param license_rule: License Rule.
:type license_rule: :class:`AccessLevel <azure.devops.v7_1.member_entitlement_management.models.AccessLevel>`
:param members: Group members. Only used when creating a new group.
:type members: list of :class:`UserEntitlement <azure.devops.v7_1.member_entitlement_management.models.UserEntitlement>`
:param project_entitlements: Relation between a project and the member's effective permissions in that project.
:type project_entitlements: list of :class:`ProjectEntitlement <azure.devops.v7_1.member_entitlement_management.models.ProjectEntitlement>`
:param status: The status of the group rule.
:type status: object
"""
_attribute_map = {
'extension_rules': {'key': 'extensionRules', 'type': '[Extension]'},
'group': {'key': 'group', 'type': 'GraphGroup'},
'id': {'key': 'id', 'type': 'str'},
'last_executed': {'key': 'lastExecuted', 'type': 'iso-8601'},
'license_rule': {'key': 'licenseRule', 'type': 'AccessLevel'},
'members': {'key': 'members', 'type': '[UserEntitlement]'},
'project_entitlements': {'key': 'projectEntitlements', 'type': '[ProjectEntitlement]'},
'status': {'key': 'status', 'type': 'object'}
}
def __init__(self, extension_rules=None, group=None, id=None, last_executed=None, license_rule=None, members=None, project_entitlements=None, status=None):
super(GroupEntitlement, self).__init__()
self.extension_rules = extension_rules
self.group = group
self.id = id
self.last_executed = last_executed
self.license_rule = license_rule
self.members = members
self.project_entitlements = project_entitlements
self.status = status
class GroupOperationResult(BaseOperationResult):
"""
:param errors: List of error codes paired with their corresponding error messages
:type errors: list of { key: int; value: str }
:param is_success: Success status of the operation
:type is_success: bool
:param group_id: Identifier of the Group being acted upon
:type group_id: str
:param result: Result of the Groupentitlement after the operation
:type result: :class:`GroupEntitlement <azure.devops.v7_1.member_entitlement_management.models.GroupEntitlement>`
"""
_attribute_map = {
'errors': {'key': 'errors', 'type': '[{ key: int; value: str }]'},
'is_success': {'key': 'isSuccess', 'type': 'bool'},
'group_id': {'key': 'groupId', 'type': 'str'},
'result': {'key': 'result', 'type': 'GroupEntitlement'}
}
def __init__(self, errors=None, is_success=None, group_id=None, result=None):
super(GroupOperationResult, self).__init__(errors=errors, is_success=is_success)
self.group_id = group_id
self.result = result
class GroupOption(Model):
"""
Group option to add a user to
:param access_level: Access Level
:type access_level: :class:`AccessLevel <azure.devops.v7_1.member_entitlement_management.models.AccessLevel>`
:param group: Group
:type group: :class:`Group <azure.devops.v7_1.member_entitlement_management.models.Group>`
"""
_attribute_map = {
'access_level': {'key': 'accessLevel', 'type': 'AccessLevel'},
'group': {'key': 'group', 'type': 'Group'}
}
def __init__(self, access_level=None, group=None):
super(GroupOption, self).__init__()
self.access_level = access_level
self.group = group
class JsonPatchOperation(Model):
"""
The JSON model for a JSON Patch operation
:param from_: The path to copy from for the Move/Copy operation.
:type from_: str
:param op: The patch operation
:type op: object
:param path: The path for the operation. In the case of an array, a zero based index can be used to specify the position in the array (e.g. /biscuits/0/name). The "-" character can be used instead of an index to insert at the end of the array (e.g. /biscuits/-).
:type path: str
:param value: The value for the operation. This is either a primitive or a JToken.
:type value: object
"""
_attribute_map = {
'from_': {'key': 'from', 'type': 'str'},
'op': {'key': 'op', 'type': 'object'},
'path': {'key': 'path', 'type': 'str'},
'value': {'key': 'value', 'type': 'object'}
}
def __init__(self, from_=None, op=None, path=None, value=None):
super(JsonPatchOperation, self).__init__()
self.from_ = from_
self.op = op
self.path = path
self.value = value
class MemberEntitlement2(EntitlementBase):
"""
An AAD member entity
:param access_level: Member's access level denoted by a license.
:type access_level: :class:`AccessLevel <azure.devops.v7_1.member_entitlement_management.models.AccessLevel>`
:param date_created: [Readonly] Date the member was added to the collection.
:type date_created: datetime
:param group_assignments: [Readonly] GroupEntitlements that this member belongs to.
:type group_assignments: list of :class:`GroupEntitlement <azure.devops.v7_1.member_entitlement_management.models.GroupEntitlement>`
:param id: The unique identifier which matches the Id of the Identity associated with the GraphMember.
:type id: str
:param last_accessed_date: [Readonly] Date the member last accessed the collection.
:type last_accessed_date: datetime
:param project_entitlements: Relation between a project and the member's effective permissions in that project.
:type project_entitlements: list of :class:`ProjectEntitlement <azure.devops.v7_1.member_entitlement_management.models.ProjectEntitlement>`
:param member:
:type member: :class:`AadGraphMember <azure.devops.v7_1.member_entitlement_management.models.AadGraphMember>`
"""
_attribute_map = {
'access_level': {'key': 'accessLevel', 'type': 'AccessLevel'},
'date_created': {'key': 'dateCreated', 'type': 'iso-8601'},
'group_assignments': {'key': 'groupAssignments', 'type': '[GroupEntitlement]'},
'id': {'key': 'id', 'type': 'str'},
'last_accessed_date': {'key': 'lastAccessedDate', 'type': 'iso-8601'},
'project_entitlements': {'key': 'projectEntitlements', 'type': '[ProjectEntitlement]'},
'member': {'key': 'member', 'type': 'AadGraphMember'}
}
def __init__(self, access_level=None, date_created=None, group_assignments=None, id=None, last_accessed_date=None, project_entitlements=None, member=None):
super(MemberEntitlement2, self).__init__(access_level=access_level, date_created=date_created, group_assignments=group_assignments, id=id, last_accessed_date=last_accessed_date, project_entitlements=project_entitlements)
self.member = member
class MemberEntitlement2OperationResult(EntitlementOperationResultBase):
"""
:param member_id: Identifier of the Member being acted upon.
:type member_id: str
"""
_attribute_map = {
'member_id': {'key': 'memberId', 'type': 'str'}
}
def __init__(self, member_id=None):
super(MemberEntitlement2OperationResult, self).__init__()
self.member_id = member_id
class MemberEntitlement2ResponseBase(Model):
"""
:param is_success: True if all operations were successful.
:type is_success: bool
:param member_entitlement: Result of the member entitlement after the operations. have been applied
:type member_entitlement: :class:`MemberEntitlement2 <azure.devops.v7_1.member_entitlement_management.models.MemberEntitlement2>`
"""
_attribute_map = {
'is_success': {'key': 'isSuccess', 'type': 'bool'},
'member_entitlement': {'key': 'memberEntitlement', 'type': 'MemberEntitlement2'}
}
def __init__(self, is_success=None, member_entitlement=None):
super(MemberEntitlement2ResponseBase, self).__init__()
self.is_success = is_success
self.member_entitlement = member_entitlement
class MemberEntitlementsResponseBase(Model):
"""
:param is_success: True if all operations were successful.
:type is_success: bool
:param member_entitlement: Result of the member entitlement after the operations. have been applied
:type member_entitlement: :class:`MemberEntitlement <azure.devops.v7_1.member_entitlement_management.models.MemberEntitlement>`
"""
_attribute_map = {
'is_success': {'key': 'isSuccess', 'type': 'bool'},
'member_entitlement': {'key': 'memberEntitlement', 'type': 'MemberEntitlement'}
}
def __init__(self, is_success=None, member_entitlement=None):
super(MemberEntitlementsResponseBase, self).__init__()
self.is_success = is_success
self.member_entitlement = member_entitlement
class OperationReference(Model):
"""
Reference for an async operation.
:param id: Unique identifier for the operation.
:type id: str
:param plugin_id: Unique identifier for the plugin.
:type plugin_id: str
:param status: The current status of the operation.
:type status: object
:param url: URL to get the full operation object.
:type url: str
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'plugin_id': {'key': 'pluginId', 'type': 'str'},
'status': {'key': 'status', 'type': 'object'},
'url': {'key': 'url', 'type': 'str'}
}
def __init__(self, id=None, plugin_id=None, status=None, url=None):
super(OperationReference, self).__init__()
self.id = id
self.plugin_id = plugin_id
self.status = status
self.url = url
class OperationResult(Model):
"""
:param errors: List of error codes paired with their corresponding error messages.
:type errors: list of { key: int; value: str }
:param is_success: Success status of the operation.
:type is_success: bool
:param member_id: Identifier of the Member being acted upon.
:type member_id: str
:param result: Result of the MemberEntitlement after the operation.
:type result: :class:`MemberEntitlement <azure.devops.v7_1.member_entitlement_management.models.MemberEntitlement>`
"""
_attribute_map = {
'errors': {'key': 'errors', 'type': '[{ key: int; value: str }]'},
'is_success': {'key': 'isSuccess', 'type': 'bool'},
'member_id': {'key': 'memberId', 'type': 'str'},
'result': {'key': 'result', 'type': 'MemberEntitlement'}
}
def __init__(self, errors=None, is_success=None, member_id=None, result=None):
super(OperationResult, self).__init__()
self.errors = errors
self.is_success = is_success
self.member_id = member_id
self.result = result
class PagedList(Model):
"""
:param continuation_token:
:type continuation_token: str
:param items:
:type items: list of object
:param total_count:
:type total_count: int
"""
_attribute_map = {
'continuation_token': {'key': 'continuationToken', 'type': 'str'},
'items': {'key': 'items', 'type': '[object]'},
'total_count': {'key': 'totalCount', 'type': 'int'}
}
def __init__(self, continuation_token=None, items=None, total_count=None):
super(PagedList, self).__init__()
self.continuation_token = continuation_token
self.items = items
self.total_count = total_count
class ProjectEntitlement(Model):
"""
Relation between a project and the user's effective permissions in that project.
:param assignment_source: Assignment Source (e.g. Group or Unknown).
:type assignment_source: object
:param group: Project Group (e.g. Contributor, Reader etc.)
:type group: :class:`Group <azure.devops.v7_1.member_entitlement_management.models.Group>`
:param is_project_permission_inherited: [Deprecated] Whether the user is inheriting permissions to a project through a Azure DevOps or AAD group membership.
:type is_project_permission_inherited: bool
:param project_permission_inherited: Whether the user is inheriting permissions to a project through a Azure DevOps or AAD group membership.
:type project_permission_inherited: object
:param project_ref: Project Ref
:type project_ref: :class:`ProjectRef <azure.devops.v7_1.member_entitlement_management.models.ProjectRef>`
:param team_refs: Team Ref.
:type team_refs: list of :class:`TeamRef <azure.devops.v7_1.member_entitlement_management.models.TeamRef>`
"""
_attribute_map = {
'assignment_source': {'key': 'assignmentSource', 'type': 'object'},
'group': {'key': 'group', 'type': 'Group'},
'is_project_permission_inherited': {'key': 'isProjectPermissionInherited', 'type': 'bool'},
'project_permission_inherited': {'key': 'projectPermissionInherited', 'type': 'object'},
'project_ref': {'key': 'projectRef', 'type': 'ProjectRef'},
'team_refs': {'key': 'teamRefs', 'type': '[TeamRef]'}
}
def __init__(self, assignment_source=None, group=None, is_project_permission_inherited=None, project_permission_inherited=None, project_ref=None, team_refs=None):
super(ProjectEntitlement, self).__init__()
self.assignment_source = assignment_source
self.group = group
self.is_project_permission_inherited = is_project_permission_inherited
self.project_permission_inherited = project_permission_inherited
self.project_ref = project_ref
self.team_refs = team_refs
class ProjectRef(Model):
"""
A reference to a project
:param id: Project ID.
:type id: str
:param name: Project Name.
:type name: str
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'}
}
def __init__(self, id=None, name=None):
super(ProjectRef, self).__init__()
self.id = id
self.name = name
class ReferenceLinks(Model):
"""
The class to represent a collection of REST reference links.
:param links: The readonly view of the links. Because Reference links are readonly, we only want to expose them as read only.
:type links: dict
"""
_attribute_map = {
'links': {'key': 'links', 'type': '{object}'}
}
def __init__(self, links=None):
super(ReferenceLinks, self).__init__()
self.links = links
class ServicePrincipalEntitlement(EntitlementBase):
"""
:param access_level: Member's access level denoted by a license.
:type access_level: :class:`AccessLevel <azure.devops.v7_1.member_entitlement_management.models.AccessLevel>`
:param date_created: [Readonly] Date the member was added to the collection.
:type date_created: datetime
:param group_assignments: [Readonly] GroupEntitlements that this member belongs to.
:type group_assignments: list of :class:`GroupEntitlement <azure.devops.v7_1.member_entitlement_management.models.GroupEntitlement>`
:param id: The unique identifier which matches the Id of the Identity associated with the GraphMember.
:type id: str
:param last_accessed_date: [Readonly] Date the member last accessed the collection.
:type last_accessed_date: datetime
:param project_entitlements: Relation between a project and the member's effective permissions in that project.
:type project_entitlements: list of :class:`ProjectEntitlement <azure.devops.v7_1.member_entitlement_management.models.ProjectEntitlement>`
:param service_principal: ServicePrincipal reference.
:type service_principal: :class:`GraphServicePrincipal <azure.devops.v7_1.member_entitlement_management.models.GraphServicePrincipal>`
"""
_attribute_map = {
'access_level': {'key': 'accessLevel', 'type': 'AccessLevel'},
'date_created': {'key': 'dateCreated', 'type': 'iso-8601'},
'group_assignments': {'key': 'groupAssignments', 'type': '[GroupEntitlement]'},
'id': {'key': 'id', 'type': 'str'},
'last_accessed_date': {'key': 'lastAccessedDate', 'type': 'iso-8601'},
'project_entitlements': {'key': 'projectEntitlements', 'type': '[ProjectEntitlement]'},
'service_principal': {'key': 'servicePrincipal', 'type': 'GraphServicePrincipal'}
}
def __init__(self, access_level=None, date_created=None, group_assignments=None, id=None, last_accessed_date=None, project_entitlements=None, service_principal=None):
super(ServicePrincipalEntitlement, self).__init__(access_level=access_level, date_created=date_created, group_assignments=group_assignments, id=id, last_accessed_date=last_accessed_date, project_entitlements=project_entitlements)
self.service_principal = service_principal
class ServicePrincipalEntitlementOperationReference(OperationReference):
"""
:param id: Unique identifier for the operation.
:type id: str
:param plugin_id: Unique identifier for the plugin.
:type plugin_id: str
:param status: The current status of the operation.
:type status: object
:param url: URL to get the full operation object.
:type url: str
:param completed: Operation completed with success or failure.
:type completed: bool
:param have_results_succeeded: True if all operations were successful.
:type have_results_succeeded: bool
:param results: List of results for each operation.
:type results: list of :class:`ServicePrincipalEntitlementOperationResult <azure.devops.v7_1.member_entitlement_management.models.ServicePrincipalEntitlementOperationResult>`
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'plugin_id': {'key': 'pluginId', 'type': 'str'},
'status': {'key': 'status', 'type': 'object'},
'url': {'key': 'url', 'type': 'str'},
'completed': {'key': 'completed', 'type': 'bool'},
'have_results_succeeded': {'key': 'haveResultsSucceeded', 'type': 'bool'},
'results': {'key': 'results', 'type': '[ServicePrincipalEntitlementOperationResult]'}
}
def __init__(self, id=None, plugin_id=None, status=None, url=None, completed=None, have_results_succeeded=None, results=None):
super(ServicePrincipalEntitlementOperationReference, self).__init__(id=id, plugin_id=plugin_id, status=status, url=url)
self.completed = completed
self.have_results_succeeded = have_results_succeeded
self.results = results
class ServicePrincipalEntitlementOperationResult(EntitlementOperationResultBase):
"""
:param service_principal_id: Identifier of the ServicePrincipal being acted upon.
:type service_principal_id: str
"""
_attribute_map = {
'service_principal_id': {'key': 'servicePrincipalId', 'type': 'str'}
}
def __init__(self, service_principal_id=None):
super(ServicePrincipalEntitlementOperationResult, self).__init__()
self.service_principal_id = service_principal_id
class ServicePrincipalEntitlementsResponseBase(Model):
"""
:param is_success:
:type is_success: bool
:param service_principal_entitlement:
:type service_principal_entitlement: :class:`ServicePrincipalEntitlement <azure.devops.v7_1.member_entitlement_management.models.ServicePrincipalEntitlement>`
"""
_attribute_map = {
'is_success': {'key': 'isSuccess', 'type': 'bool'},
'service_principal_entitlement': {'key': 'servicePrincipalEntitlement', 'type': 'ServicePrincipalEntitlement'}
}
def __init__(self, is_success=None, service_principal_entitlement=None):
super(ServicePrincipalEntitlementsResponseBase, self).__init__()
self.is_success = is_success
self.service_principal_entitlement = service_principal_entitlement
class SummaryData(Model):
"""
:param assigned: Count of Licenses already assigned.
:type assigned: int
:param available: Available Count.
:type available: int
:param included_quantity: Quantity
:type included_quantity: int
:param total: Total Count.
:type total: int
"""
_attribute_map = {
'assigned': {'key': 'assigned', 'type': 'int'},
'available': {'key': 'available', 'type': 'int'},
'included_quantity': {'key': 'includedQuantity', 'type': 'int'},
'total': {'key': 'total', 'type': 'int'}
}
def __init__(self, assigned=None, available=None, included_quantity=None, total=None):
super(SummaryData, self).__init__()
self.assigned = assigned
self.available = available
self.included_quantity = included_quantity
self.total = total
class TeamRef(Model):
"""
A reference to a team
:param id: Team ID
:type id: str
:param name: Team Name
:type name: str
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'}
}
def __init__(self, id=None, name=None):
super(TeamRef, self).__init__()
self.id = id
self.name = name
class UserEntitlement(EntitlementBase):
"""
A user entity with additional properties including their license, extensions, and project membership
:param access_level: Member's access level denoted by a license.
:type access_level: :class:`AccessLevel <azure.devops.v7_1.member_entitlement_management.models.AccessLevel>`
:param date_created: [Readonly] Date the member was added to the collection.
:type date_created: datetime
:param group_assignments: [Readonly] GroupEntitlements that this member belongs to.
:type group_assignments: list of :class:`GroupEntitlement <azure.devops.v7_1.member_entitlement_management.models.GroupEntitlement>`
:param id: The unique identifier which matches the Id of the Identity associated with the GraphMember.
:type id: str
:param last_accessed_date: [Readonly] Date the member last accessed the collection.
:type last_accessed_date: datetime
:param project_entitlements: Relation between a project and the member's effective permissions in that project.
:type project_entitlements: list of :class:`ProjectEntitlement <azure.devops.v7_1.member_entitlement_management.models.ProjectEntitlement>`
:param extensions: User's extensions.
:type extensions: list of :class:`Extension <azure.devops.v7_1.member_entitlement_management.models.Extension>`
:param user: User reference.
:type user: :class:`GraphUser <azure.devops.v7_1.member_entitlement_management.models.GraphUser>`
"""
_attribute_map = {
'access_level': {'key': 'accessLevel', 'type': 'AccessLevel'},
'date_created': {'key': 'dateCreated', 'type': 'iso-8601'},
'group_assignments': {'key': 'groupAssignments', 'type': '[GroupEntitlement]'},
'id': {'key': 'id', 'type': 'str'},
'last_accessed_date': {'key': 'lastAccessedDate', 'type': 'iso-8601'},
'project_entitlements': {'key': 'projectEntitlements', 'type': '[ProjectEntitlement]'},
'extensions': {'key': 'extensions', 'type': '[Extension]'},
'user': {'key': 'user', 'type': 'GraphUser'}
}
def __init__(self, access_level=None, date_created=None, group_assignments=None, id=None, last_accessed_date=None, project_entitlements=None, extensions=None, user=None):
super(UserEntitlement, self).__init__(access_level=access_level, date_created=date_created, group_assignments=group_assignments, id=id, last_accessed_date=last_accessed_date, project_entitlements=project_entitlements)
self.extensions = extensions
self.user = user
class UserEntitlementOperationReference(OperationReference):
"""
:param id: Unique identifier for the operation.
:type id: str
:param plugin_id: Unique identifier for the plugin.
:type plugin_id: str
:param status: The current status of the operation.
:type status: object
:param url: URL to get the full operation object.
:type url: str
:param completed: Operation completed with success or failure.
:type completed: bool
:param have_results_succeeded: True if all operations were successful.
:type have_results_succeeded: bool
:param results: List of results for each operation.
:type results: list of :class:`UserEntitlementOperationResult <azure.devops.v7_1.member_entitlement_management.models.UserEntitlementOperationResult>`
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'plugin_id': {'key': 'pluginId', 'type': 'str'},
'status': {'key': 'status', 'type': 'object'},
'url': {'key': 'url', 'type': 'str'},
'completed': {'key': 'completed', 'type': 'bool'},
'have_results_succeeded': {'key': 'haveResultsSucceeded', 'type': 'bool'},
'results': {'key': 'results', 'type': '[UserEntitlementOperationResult]'}
}
def __init__(self, id=None, plugin_id=None, status=None, url=None, completed=None, have_results_succeeded=None, results=None):
super(UserEntitlementOperationReference, self).__init__(id=id, plugin_id=plugin_id, status=status, url=url)
self.completed = completed
self.have_results_succeeded = have_results_succeeded
self.results = results
class UserEntitlementOperationResult(EntitlementOperationResultBase):
"""
:param user_id: Identifier of the Member being acted upon.
:type user_id: str
"""
_attribute_map = {
'user_id': {'key': 'userId', 'type': 'str'}
}
def __init__(self, user_id=None):
super(UserEntitlementOperationResult, self).__init__()
self.user_id = user_id
class UserEntitlementsResponseBase(Model):
"""
:param is_success: True if all operations were successful.
:type is_success: bool
:param user_entitlement: Result of the user entitlement after the operations have been applied.
:type user_entitlement: :class:`UserEntitlement <azure.devops.v7_1.member_entitlement_management.models.UserEntitlement>`
"""
_attribute_map = {
'is_success': {'key': 'isSuccess', 'type': 'bool'},
'user_entitlement': {'key': 'userEntitlement', 'type': 'UserEntitlement'}
}
def __init__(self, is_success=None, user_entitlement=None):
super(UserEntitlementsResponseBase, self).__init__()
self.is_success = is_success
self.user_entitlement = user_entitlement
class UsersSummary(Model):
"""
Summary of licenses and extensions assigned to users in the organization
:param available_access_levels: Available Access Levels
:type available_access_levels: list of :class:`AccessLevel <azure.devops.v7_1.member_entitlement_management.models.AccessLevel>`
:param default_access_level: Default Access Level
:type default_access_level: :class:`AccessLevel <azure.devops.v7_1.member_entitlement_management.models.AccessLevel>`
:param extensions: Summary of Extensions in the organization
:type extensions: list of :class:`ExtensionSummaryData <azure.devops.v7_1.member_entitlement_management.models.ExtensionSummaryData>`
:param group_options: Group Options
:type group_options: list of :class:`GroupOption <azure.devops.v7_1.member_entitlement_management.models.GroupOption>`
:param licenses: Summary of Licenses in the organization
:type licenses: list of :class:`LicenseSummaryData <azure.devops.v7_1.member_entitlement_management.models.LicenseSummaryData>`
:param project_refs: Summary of Projects in the organization
:type project_refs: list of :class:`ProjectRef <azure.devops.v7_1.member_entitlement_management.models.ProjectRef>`
"""
_attribute_map = {
'available_access_levels': {'key': 'availableAccessLevels', 'type': '[AccessLevel]'},
'default_access_level': {'key': 'defaultAccessLevel', 'type': 'AccessLevel'},
'extensions': {'key': 'extensions', 'type': '[ExtensionSummaryData]'},
'group_options': {'key': 'groupOptions', 'type': '[GroupOption]'},
'licenses': {'key': 'licenses', 'type': '[LicenseSummaryData]'},
'project_refs': {'key': 'projectRefs', 'type': '[ProjectRef]'}
}
def __init__(self, available_access_levels=None, default_access_level=None, extensions=None, group_options=None, licenses=None, project_refs=None):
super(UsersSummary, self).__init__()
self.available_access_levels = available_access_levels
self.default_access_level = default_access_level
self.extensions = extensions
self.group_options = group_options
self.licenses = licenses
self.project_refs = project_refs
class ExtensionSummaryData(SummaryData):
"""
Summary of Extensions in the organization.
:param assigned: Count of Licenses already assigned.
:type assigned: int
:param available: Available Count.
:type available: int
:param included_quantity: Quantity
:type included_quantity: int
:param total: Total Count.
:type total: int
:param assigned_through_subscription: Count of Extension Licenses assigned to users through msdn.
:type assigned_through_subscription: int
:param extension_id: Gallery Id of the Extension
:type extension_id: str
:param extension_name: Friendly name of this extension
:type extension_name: str
:param is_trial_version: Whether its a Trial Version.
:type is_trial_version: bool
:param minimum_license_required: Minimum License Required for the Extension.
:type minimum_license_required: object
:param remaining_trial_days: Days remaining for the Trial to expire.
:type remaining_trial_days: int
:param trial_expiry_date: Date on which the Trial expires.
:type trial_expiry_date: datetime
"""
_attribute_map = {
'assigned': {'key': 'assigned', 'type': 'int'},
'available': {'key': 'available', 'type': 'int'},
'included_quantity': {'key': 'includedQuantity', 'type': 'int'},
'total': {'key': 'total', 'type': 'int'},
'assigned_through_subscription': {'key': 'assignedThroughSubscription', 'type': 'int'},
'extension_id': {'key': 'extensionId', 'type': 'str'},
'extension_name': {'key': 'extensionName', 'type': 'str'},
'is_trial_version': {'key': 'isTrialVersion', 'type': 'bool'},
'minimum_license_required': {'key': 'minimumLicenseRequired', 'type': 'object'},
'remaining_trial_days': {'key': 'remainingTrialDays', 'type': 'int'},
'trial_expiry_date': {'key': 'trialExpiryDate', 'type': 'iso-8601'}
}
def __init__(self, assigned=None, available=None, included_quantity=None, total=None, assigned_through_subscription=None, extension_id=None, extension_name=None, is_trial_version=None, minimum_license_required=None, remaining_trial_days=None, trial_expiry_date=None):
super(ExtensionSummaryData, self).__init__(assigned=assigned, available=available, included_quantity=included_quantity, total=total)
self.assigned_through_subscription = assigned_through_subscription
self.extension_id = extension_id
self.extension_name = extension_name
self.is_trial_version = is_trial_version
self.minimum_license_required = minimum_license_required
self.remaining_trial_days = remaining_trial_days
self.trial_expiry_date = trial_expiry_date
class GraphSubject(GraphSubjectBase):
"""
Top-level graph entity
:param _links: This field contains zero or more interesting links about the graph subject. These links may be invoked to obtain additional relationships or more detailed information about this graph subject.
:type _links: :class:`ReferenceLinks <azure.devops.v7_1.microsoft._visual_studio._services._web_api.models.ReferenceLinks>`
:param descriptor: The descriptor is the primary way to reference the graph subject while the system is running. This field will uniquely identify the same graph subject across both Accounts and Organizations.
:type descriptor: str
:param display_name: This is the non-unique display name of the graph subject. To change this field, you must alter its value in the source provider.
:type display_name: str
:param url: This url is the full route to the source resource of this graph subject.
:type url: str
:param legacy_descriptor: [Internal Use Only] The legacy descriptor is here in case you need to access old version IMS using identity descriptor.
:type legacy_descriptor: str
:param origin: The type of source provider for the origin identifier (ex:AD, AAD, MSA)
:type origin: str
:param origin_id: The unique identifier from the system of origin. Typically a sid, object id or Guid. Linking and unlinking operations can cause this value to change for a user because the user is not backed by a different provider and has a different unique id in the new provider.
:type origin_id: str
:param subject_kind: This field identifies the type of the graph subject (ex: Group, Scope, User).
:type subject_kind: str
"""
_attribute_map = {
'_links': {'key': '_links', 'type': 'ReferenceLinks'},
'descriptor': {'key': 'descriptor', 'type': 'str'},
'display_name': {'key': 'displayName', 'type': 'str'},
'url': {'key': 'url', 'type': 'str'},
'legacy_descriptor': {'key': 'legacyDescriptor', 'type': 'str'},
'origin': {'key': 'origin', 'type': 'str'},
'origin_id': {'key': 'originId', 'type': 'str'},
'subject_kind': {'key': 'subjectKind', 'type': 'str'}
}
def __init__(self, _links=None, descriptor=None, display_name=None, url=None, legacy_descriptor=None, origin=None, origin_id=None, subject_kind=None):
super(GraphSubject, self).__init__(_links=_links, descriptor=descriptor, display_name=display_name, url=url)
self.legacy_descriptor = legacy_descriptor
self.origin = origin
self.origin_id = origin_id
self.subject_kind = subject_kind
class GroupEntitlementOperationReference(OperationReference):
"""
:param id: Unique identifier for the operation.
:type id: str
:param plugin_id: Unique identifier for the plugin.
:type plugin_id: str
:param status: The current status of the operation.
:type status: object
:param url: URL to get the full operation object.
:type url: str
:param completed: Operation completed with success or failure.
:type completed: bool
:param have_results_succeeded: True if all operations were successful.
:type have_results_succeeded: bool
:param results: List of results for each operation.
:type results: list of :class:`GroupOperationResult <azure.devops.v7_1.member_entitlement_management.models.GroupOperationResult>`
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'plugin_id': {'key': 'pluginId', 'type': 'str'},
'status': {'key': 'status', 'type': 'object'},
'url': {'key': 'url', 'type': 'str'},
'completed': {'key': 'completed', 'type': 'bool'},
'have_results_succeeded': {'key': 'haveResultsSucceeded', 'type': 'bool'},
'results': {'key': 'results', 'type': '[GroupOperationResult]'}
}
def __init__(self, id=None, plugin_id=None, status=None, url=None, completed=None, have_results_succeeded=None, results=None):
super(GroupEntitlementOperationReference, self).__init__(id=id, plugin_id=plugin_id, status=status, url=url)
self.completed = completed
self.have_results_succeeded = have_results_succeeded
self.results = results
class LicenseSummaryData(SummaryData):
"""
Summary of Licenses in the organization.
:param assigned: Count of Licenses already assigned.
:type assigned: int
:param available: Available Count.
:type available: int
:param included_quantity: Quantity
:type included_quantity: int
:param total: Total Count.
:type total: int
:param account_license_type: Type of Account License.
:type account_license_type: object
:param disabled: Count of Disabled Licenses.
:type disabled: int
:param is_purchasable: Designates if this license quantity can be changed through purchase
:type is_purchasable: bool
:param license_name: Name of the License.
:type license_name: str
:param msdn_license_type: Type of MSDN License.
:type msdn_license_type: object
:param next_billing_date: Specifies the date when billing will charge for paid licenses
:type next_billing_date: datetime
:param source: Source of the License.
:type source: object
:param total_after_next_billing_date: Total license count after next billing cycle
:type total_after_next_billing_date: int
"""
_attribute_map = {
'assigned': {'key': 'assigned', 'type': 'int'},
'available': {'key': 'available', 'type': 'int'},
'included_quantity': {'key': 'includedQuantity', 'type': 'int'},
'total': {'key': 'total', 'type': 'int'},
'account_license_type': {'key': 'accountLicenseType', 'type': 'object'},
'disabled': {'key': 'disabled', 'type': 'int'},
'is_purchasable': {'key': 'isPurchasable', 'type': 'bool'},
'license_name': {'key': 'licenseName', 'type': 'str'},
'msdn_license_type': {'key': 'msdnLicenseType', 'type': 'object'},
'next_billing_date': {'key': 'nextBillingDate', 'type': 'iso-8601'},
'source': {'key': 'source', 'type': 'object'},
'total_after_next_billing_date': {'key': 'totalAfterNextBillingDate', 'type': 'int'}
}
def __init__(self, assigned=None, available=None, included_quantity=None, total=None, account_license_type=None, disabled=None, is_purchasable=None, license_name=None, msdn_license_type=None, next_billing_date=None, source=None, total_after_next_billing_date=None):
super(LicenseSummaryData, self).__init__(assigned=assigned, available=available, included_quantity=included_quantity, total=total)
self.account_license_type = account_license_type
self.disabled = disabled
self.is_purchasable = is_purchasable
self.license_name = license_name
self.msdn_license_type = msdn_license_type
self.next_billing_date = next_billing_date
self.source = source
self.total_after_next_billing_date = total_after_next_billing_date
class MemberEntitlement(UserEntitlement):
"""
Deprecated: Use UserEntitlement instead
:param access_level: Member's access level denoted by a license.
:type access_level: :class:`AccessLevel <azure.devops.v7_1.member_entitlement_management.models.AccessLevel>`
:param date_created: [Readonly] Date the member was added to the collection.
:type date_created: datetime
:param group_assignments: [Readonly] GroupEntitlements that this member belongs to.
:type group_assignments: list of :class:`GroupEntitlement <azure.devops.v7_1.member_entitlement_management.models.GroupEntitlement>`
:param id: The unique identifier which matches the Id of the Identity associated with the GraphMember.
:type id: str
:param last_accessed_date: [Readonly] Date the member last accessed the collection.
:type last_accessed_date: datetime
:param project_entitlements: Relation between a project and the member's effective permissions in that project.
:type project_entitlements: list of :class:`ProjectEntitlement <azure.devops.v7_1.member_entitlement_management.models.ProjectEntitlement>`
:param extensions: User's extensions.
:type extensions: list of :class:`Extension <azure.devops.v7_1.member_entitlement_management.models.Extension>`
:param user: User reference.
:type user: :class:`GraphUser <azure.devops.v7_1.member_entitlement_management.models.GraphUser>`
:param member: Member reference
:type member: :class:`GraphMember <azure.devops.v7_1.member_entitlement_management.models.GraphMember>`
"""
_attribute_map = {
'access_level': {'key': 'accessLevel', 'type': 'AccessLevel'},
'date_created': {'key': 'dateCreated', 'type': 'iso-8601'},
'group_assignments': {'key': 'groupAssignments', 'type': '[GroupEntitlement]'},
'id': {'key': 'id', 'type': 'str'},
'last_accessed_date': {'key': 'lastAccessedDate', 'type': 'iso-8601'},
'project_entitlements': {'key': 'projectEntitlements', 'type': '[ProjectEntitlement]'},
'extensions': {'key': 'extensions', 'type': '[Extension]'},
'user': {'key': 'user', 'type': 'GraphUser'},
'member': {'key': 'member', 'type': 'GraphMember'}
}
def __init__(self, access_level=None, date_created=None, group_assignments=None, id=None, last_accessed_date=None, project_entitlements=None, extensions=None, user=None, member=None):
super(MemberEntitlement, self).__init__(access_level=access_level, date_created=date_created, group_assignments=group_assignments, id=id, last_accessed_date=last_accessed_date, project_entitlements=project_entitlements, extensions=extensions, user=user)
self.member = member
class MemberEntitlement2OperationReference(OperationReference):
"""
:param id: Unique identifier for the operation.
:type id: str
:param plugin_id: Unique identifier for the plugin.
:type plugin_id: str
:param status: The current status of the operation.
:type status: object
:param url: URL to get the full operation object.
:type url: str
:param completed: Operation completed with success or failure.
:type completed: bool
:param have_results_succeeded: True if all operations were successful.
:type have_results_succeeded: bool
:param results: List of results for each operation.
:type results: list of :class:`MemberEntitlement2OperationResult <azure.devops.v7_1.member_entitlement_management.models.MemberEntitlement2OperationResult>`
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'plugin_id': {'key': 'pluginId', 'type': 'str'},
'status': {'key': 'status', 'type': 'object'},
'url': {'key': 'url', 'type': 'str'},
'completed': {'key': 'completed', 'type': 'bool'},
'have_results_succeeded': {'key': 'haveResultsSucceeded', 'type': 'bool'},
'results': {'key': 'results', 'type': '[MemberEntitlement2OperationResult]'}
}
def __init__(self, id=None, plugin_id=None, status=None, url=None, completed=None, have_results_succeeded=None, results=None):
super(MemberEntitlement2OperationReference, self).__init__(id=id, plugin_id=plugin_id, status=status, url=url)
self.completed = completed
self.have_results_succeeded = have_results_succeeded
self.results = results
class MemberEntitlement2PatchResponse(MemberEntitlement2ResponseBase):
"""
:param is_success: True if all operations were successful.
:type is_success: bool
:param member_entitlement: Result of the member entitlement after the operations. have been applied
:type member_entitlement: :class:`MemberEntitlement2 <azure.devops.v7_1.member_entitlement_management.models.MemberEntitlement2>`
:param operation_results: List of results for each operation
:type operation_results: list of :class:`MemberEntitlement2OperationResult <azure.devops.v7_1.member_entitlement_management.models.MemberEntitlement2OperationResult>`
"""
_attribute_map = {
'is_success': {'key': 'isSuccess', 'type': 'bool'},
'member_entitlement': {'key': 'memberEntitlement', 'type': 'MemberEntitlement2'},
'operation_results': {'key': 'operationResults', 'type': '[MemberEntitlement2OperationResult]'}
}
def __init__(self, is_success=None, member_entitlement=None, operation_results=None):
super(MemberEntitlement2PatchResponse, self).__init__(is_success=is_success, member_entitlement=member_entitlement)
self.operation_results = operation_results
class MemberEntitlement2PostResponse(MemberEntitlement2ResponseBase):
"""
:param is_success: True if all operations were successful.
:type is_success: bool
:param member_entitlement: Result of the member entitlement after the operations. have been applied
:type member_entitlement: :class:`MemberEntitlement2 <azure.devops.v7_1.member_entitlement_management.models.MemberEntitlement2>`
:param operation_result: Operation result
:type operation_result: :class:`MemberEntitlement2OperationResult <azure.devops.v7_1.member_entitlement_management.models.MemberEntitlement2OperationResult>`
"""
_attribute_map = {
'is_success': {'key': 'isSuccess', 'type': 'bool'},
'member_entitlement': {'key': 'memberEntitlement', 'type': 'MemberEntitlement2'},
'operation_result': {'key': 'operationResult', 'type': 'MemberEntitlement2OperationResult'}
}
def __init__(self, is_success=None, member_entitlement=None, operation_result=None):
super(MemberEntitlement2PostResponse, self).__init__(is_success=is_success, member_entitlement=member_entitlement)
self.operation_result = operation_result
class MemberEntitlementOperationReference(OperationReference):
"""
:param id: Unique identifier for the operation.
:type id: str
:param plugin_id: Unique identifier for the plugin.
:type plugin_id: str
:param status: The current status of the operation.
:type status: object
:param url: URL to get the full operation object.
:type url: str
:param completed: Operation completed with success or failure
:type completed: bool
:param have_results_succeeded: True if all operations were successful
:type have_results_succeeded: bool
:param results: List of results for each operation
:type results: list of :class:`OperationResult <azure.devops.v7_1.member_entitlement_management.models.OperationResult>`
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'plugin_id': {'key': 'pluginId', 'type': 'str'},
'status': {'key': 'status', 'type': 'object'},
'url': {'key': 'url', 'type': 'str'},
'completed': {'key': 'completed', 'type': 'bool'},
'have_results_succeeded': {'key': 'haveResultsSucceeded', 'type': 'bool'},
'results': {'key': 'results', 'type': '[OperationResult]'}
}
def __init__(self, id=None, plugin_id=None, status=None, url=None, completed=None, have_results_succeeded=None, results=None):
super(MemberEntitlementOperationReference, self).__init__(id=id, plugin_id=plugin_id, status=status, url=url)
self.completed = completed
self.have_results_succeeded = have_results_succeeded
self.results = results
class MemberEntitlementsPatchResponse(MemberEntitlementsResponseBase):
"""
:param is_success: True if all operations were successful.
:type is_success: bool
:param member_entitlement: Result of the member entitlement after the operations. have been applied
:type member_entitlement: :class:`MemberEntitlement <azure.devops.v7_1.member_entitlement_management.models.MemberEntitlement>`
:param operation_results: List of results for each operation
:type operation_results: list of :class:`OperationResult <azure.devops.v7_1.member_entitlement_management.models.OperationResult>`
"""
_attribute_map = {
'is_success': {'key': 'isSuccess', 'type': 'bool'},
'member_entitlement': {'key': 'memberEntitlement', 'type': 'MemberEntitlement'},
'operation_results': {'key': 'operationResults', 'type': '[OperationResult]'}
}
def __init__(self, is_success=None, member_entitlement=None, operation_results=None):
super(MemberEntitlementsPatchResponse, self).__init__(is_success=is_success, member_entitlement=member_entitlement)
self.operation_results = operation_results
class MemberEntitlementsPostResponse(MemberEntitlementsResponseBase):
"""
:param is_success: True if all operations were successful.
:type is_success: bool
:param member_entitlement: Result of the member entitlement after the operations. have been applied
:type member_entitlement: :class:`MemberEntitlement <azure.devops.v7_1.member_entitlement_management.models.MemberEntitlement>`
:param operation_result: Operation result
:type operation_result: :class:`OperationResult <azure.devops.v7_1.member_entitlement_management.models.OperationResult>`
"""
_attribute_map = {
'is_success': {'key': 'isSuccess', 'type': 'bool'},
'member_entitlement': {'key': 'memberEntitlement', 'type': 'MemberEntitlement'},
'operation_result': {'key': 'operationResult', 'type': 'OperationResult'}
}
def __init__(self, is_success=None, member_entitlement=None, operation_result=None):
super(MemberEntitlementsPostResponse, self).__init__(is_success=is_success, member_entitlement=member_entitlement)
self.operation_result = operation_result
class PagedGraphMemberList(PagedList):
"""
A page of users
:param members:
:type members: list of :class:`UserEntitlement <azure.devops.v7_1.member_entitlement_management.models.UserEntitlement>`
"""
_attribute_map = {
'members': {'key': 'members', 'type': '[UserEntitlement]'}
}
def __init__(self, members=None):
super(PagedGraphMemberList, self).__init__()
self.members = members
class ServicePrincipalEntitlementsPatchResponse(ServicePrincipalEntitlementsResponseBase):
"""
:param is_success:
:type is_success: bool
:param service_principal_entitlement:
:type service_principal_entitlement: :class:`ServicePrincipalEntitlement <azure.devops.v7_1.member_entitlement_management.models.ServicePrincipalEntitlement>`
:param operation_results:
:type operation_results: list of :class:`ServicePrincipalEntitlementOperationResult <azure.devops.v7_1.member_entitlement_management.models.ServicePrincipalEntitlementOperationResult>`
"""
_attribute_map = {
'is_success': {'key': 'isSuccess', 'type': 'bool'},
'service_principal_entitlement': {'key': 'servicePrincipalEntitlement', 'type': 'ServicePrincipalEntitlement'},
'operation_results': {'key': 'operationResults', 'type': '[ServicePrincipalEntitlementOperationResult]'}
}
def __init__(self, is_success=None, service_principal_entitlement=None, operation_results=None):
super(ServicePrincipalEntitlementsPatchResponse, self).__init__(is_success=is_success, service_principal_entitlement=service_principal_entitlement)
self.operation_results = operation_results
class ServicePrincipalEntitlementsPostResponse(ServicePrincipalEntitlementsResponseBase):
"""
:param is_success:
:type is_success: bool
:param service_principal_entitlement:
:type service_principal_entitlement: :class:`ServicePrincipalEntitlement <azure.devops.v7_1.member_entitlement_management.models.ServicePrincipalEntitlement>`
:param operation_result:
:type operation_result: :class:`ServicePrincipalEntitlementOperationResult <azure.devops.v7_1.member_entitlement_management.models.ServicePrincipalEntitlementOperationResult>`
"""
_attribute_map = {
'is_success': {'key': 'isSuccess', 'type': 'bool'},
'service_principal_entitlement': {'key': 'servicePrincipalEntitlement', 'type': 'ServicePrincipalEntitlement'},
'operation_result': {'key': 'operationResult', 'type': 'ServicePrincipalEntitlementOperationResult'}
}
def __init__(self, is_success=None, service_principal_entitlement=None, operation_result=None):
super(ServicePrincipalEntitlementsPostResponse, self).__init__(is_success=is_success, service_principal_entitlement=service_principal_entitlement)
self.operation_result = operation_result
class UserEntitlementsPatchResponse(UserEntitlementsResponseBase):
"""
:param is_success: True if all operations were successful.
:type is_success: bool
:param user_entitlement: Result of the user entitlement after the operations have been applied.
:type user_entitlement: :class:`UserEntitlement <azure.devops.v7_1.member_entitlement_management.models.UserEntitlement>`
:param operation_results: List of results for each operation.
:type operation_results: list of :class:`UserEntitlementOperationResult <azure.devops.v7_1.member_entitlement_management.models.UserEntitlementOperationResult>`
"""
_attribute_map = {
'is_success': {'key': 'isSuccess', 'type': 'bool'},
'user_entitlement': {'key': 'userEntitlement', 'type': 'UserEntitlement'},
'operation_results': {'key': 'operationResults', 'type': '[UserEntitlementOperationResult]'}
}
def __init__(self, is_success=None, user_entitlement=None, operation_results=None):
super(UserEntitlementsPatchResponse, self).__init__(is_success=is_success, user_entitlement=user_entitlement)
self.operation_results = operation_results
class UserEntitlementsPostResponse(UserEntitlementsResponseBase):
"""
:param is_success: True if all operations were successful.
:type is_success: bool
:param user_entitlement: Result of the user entitlement after the operations have been applied.
:type user_entitlement: :class:`UserEntitlement <azure.devops.v7_1.member_entitlement_management.models.UserEntitlement>`
:param operation_result: Operation result.
:type operation_result: :class:`UserEntitlementOperationResult <azure.devops.v7_1.member_entitlement_management.models.UserEntitlementOperationResult>`
"""
_attribute_map = {
'is_success': {'key': 'isSuccess', 'type': 'bool'},
'user_entitlement': {'key': 'userEntitlement', 'type': 'UserEntitlement'},
'operation_result': {'key': 'operationResult', 'type': 'UserEntitlementOperationResult'}
}
def __init__(self, is_success=None, user_entitlement=None, operation_result=None):
super(UserEntitlementsPostResponse, self).__init__(is_success=is_success, user_entitlement=user_entitlement)
self.operation_result = operation_result
class GraphMember(GraphSubject):
"""
:param _links: This field contains zero or more interesting links about the graph subject. These links may be invoked to obtain additional relationships or more detailed information about this graph subject.
:type _links: :class:`ReferenceLinks <azure.devops.v7_1.microsoft._visual_studio._services._web_api.models.ReferenceLinks>`
:param descriptor: The descriptor is the primary way to reference the graph subject while the system is running. This field will uniquely identify the same graph subject across both Accounts and Organizations.
:type descriptor: str
:param display_name: This is the non-unique display name of the graph subject. To change this field, you must alter its value in the source provider.
:type display_name: str
:param url: This url is the full route to the source resource of this graph subject.
:type url: str
:param legacy_descriptor: [Internal Use Only] The legacy descriptor is here in case you need to access old version IMS using identity descriptor.
:type legacy_descriptor: str
:param origin: The type of source provider for the origin identifier (ex:AD, AAD, MSA)
:type origin: str
:param origin_id: The unique identifier from the system of origin. Typically a sid, object id or Guid. Linking and unlinking operations can cause this value to change for a user because the user is not backed by a different provider and has a different unique id in the new provider.
:type origin_id: str
:param subject_kind: This field identifies the type of the graph subject (ex: Group, Scope, User).
:type subject_kind: str
:param domain: This represents the name of the container of origin for a graph member. (For MSA this is "Windows Live ID", for AD the name of the domain, for AAD the tenantID of the directory, for VSTS groups the ScopeId, etc)
:type domain: str
:param mail_address: The email address of record for a given graph member. This may be different than the principal name.
:type mail_address: str
:param principal_name: This is the PrincipalName of this graph member from the source provider. The source provider may change this field over time and it is not guaranteed to be immutable for the life of the graph member by VSTS.
:type principal_name: str
"""
_attribute_map = {
'_links': {'key': '_links', 'type': 'ReferenceLinks'},
'descriptor': {'key': 'descriptor', 'type': 'str'},
'display_name': {'key': 'displayName', 'type': 'str'},
'url': {'key': 'url', 'type': 'str'},
'legacy_descriptor': {'key': 'legacyDescriptor', 'type': 'str'},
'origin': {'key': 'origin', 'type': 'str'},
'origin_id': {'key': 'originId', 'type': 'str'},
'subject_kind': {'key': 'subjectKind', 'type': 'str'},
'domain': {'key': 'domain', 'type': 'str'},
'mail_address': {'key': 'mailAddress', 'type': 'str'},
'principal_name': {'key': 'principalName', 'type': 'str'}
}
def __init__(self, _links=None, descriptor=None, display_name=None, url=None, legacy_descriptor=None, origin=None, origin_id=None, subject_kind=None, domain=None, mail_address=None, principal_name=None):
super(GraphMember, self).__init__(_links=_links, descriptor=descriptor, display_name=display_name, url=url, legacy_descriptor=legacy_descriptor, origin=origin, origin_id=origin_id, subject_kind=subject_kind)
self.domain = domain
self.mail_address = mail_address
self.principal_name = principal_name
class AadGraphMember(GraphMember):
"""
:param _links: This field contains zero or more interesting links about the graph subject. These links may be invoked to obtain additional relationships or more detailed information about this graph subject.
:type _links: :class:`ReferenceLinks <azure.devops.v7_1.microsoft._visual_studio._services._web_api.models.ReferenceLinks>`
:param descriptor: The descriptor is the primary way to reference the graph subject while the system is running. This field will uniquely identify the same graph subject across both Accounts and Organizations.
:type descriptor: str
:param display_name: This is the non-unique display name of the graph subject. To change this field, you must alter its value in the source provider.
:type display_name: str
:param url: This url is the full route to the source resource of this graph subject.
:type url: str
:param legacy_descriptor: [Internal Use Only] The legacy descriptor is here in case you need to access old version IMS using identity descriptor.
:type legacy_descriptor: str
:param origin: The type of source provider for the origin identifier (ex:AD, AAD, MSA)
:type origin: str
:param origin_id: The unique identifier from the system of origin. Typically a sid, object id or Guid. Linking and unlinking operations can cause this value to change for a user because the user is not backed by a different provider and has a different unique id in the new provider.
:type origin_id: str
:param subject_kind: This field identifies the type of the graph subject (ex: Group, Scope, User).
:type subject_kind: str
:param domain: This represents the name of the container of origin for a graph member. (For MSA this is "Windows Live ID", for AD the name of the domain, for AAD the tenantID of the directory, for VSTS groups the ScopeId, etc)
:type domain: str
:param mail_address: The email address of record for a given graph member. This may be different than the principal name.
:type mail_address: str
:param principal_name: This is the PrincipalName of this graph member from the source provider. The source provider may change this field over time and it is not guaranteed to be immutable for the life of the graph member by VSTS.
:type principal_name: str
:param directory_alias: The short, generally unique name for the user in the backing directory. For AAD users, this corresponds to the mail nickname, which is often but not necessarily similar to the part of the user's mail address before the @ sign. For GitHub users, this corresponds to the GitHub user handle.
:type directory_alias: str
:param is_deleted_in_origin: When true, the group has been deleted in the identity provider
:type is_deleted_in_origin: bool
:param metadata_update_date:
:type metadata_update_date: datetime
:param meta_type: The meta type of the user in the origin, such as "member", "guest", etc. See UserMetaType for the set of possible values.
:type meta_type: str
"""
_attribute_map = {
'_links': {'key': '_links', 'type': 'ReferenceLinks'},
'descriptor': {'key': 'descriptor', 'type': 'str'},
'display_name': {'key': 'displayName', 'type': 'str'},
'url': {'key': 'url', 'type': 'str'},
'legacy_descriptor': {'key': 'legacyDescriptor', 'type': 'str'},
'origin': {'key': 'origin', 'type': 'str'},
'origin_id': {'key': 'originId', 'type': 'str'},
'subject_kind': {'key': 'subjectKind', 'type': 'str'},
'domain': {'key': 'domain', 'type': 'str'},
'mail_address': {'key': 'mailAddress', 'type': 'str'},
'principal_name': {'key': 'principalName', 'type': 'str'},
'directory_alias': {'key': 'directoryAlias', 'type': 'str'},
'is_deleted_in_origin': {'key': 'isDeletedInOrigin', 'type': 'bool'},
'metadata_update_date': {'key': 'metadataUpdateDate', 'type': 'iso-8601'},
'meta_type': {'key': 'metaType', 'type': 'str'}
}
def __init__(self, _links=None, descriptor=None, display_name=None, url=None, legacy_descriptor=None, origin=None, origin_id=None, subject_kind=None, domain=None, mail_address=None, principal_name=None, directory_alias=None, is_deleted_in_origin=None, metadata_update_date=None, meta_type=None):
super(AadGraphMember, self).__init__(_links=_links, descriptor=descriptor, display_name=display_name, url=url, legacy_descriptor=legacy_descriptor, origin=origin, origin_id=origin_id, subject_kind=subject_kind, domain=domain, mail_address=mail_address, principal_name=principal_name)
self.directory_alias = directory_alias
self.is_deleted_in_origin = is_deleted_in_origin
self.metadata_update_date = metadata_update_date
self.meta_type = meta_type
class GraphGroup(GraphMember):
"""
Graph group entity
:param _links: This field contains zero or more interesting links about the graph subject. These links may be invoked to obtain additional relationships or more detailed information about this graph subject.
:type _links: :class:`ReferenceLinks <azure.devops.v7_1.microsoft._visual_studio._services._web_api.models.ReferenceLinks>`
:param descriptor: The descriptor is the primary way to reference the graph subject while the system is running. This field will uniquely identify the same graph subject across both Accounts and Organizations.
:type descriptor: str
:param display_name: This is the non-unique display name of the graph subject. To change this field, you must alter its value in the source provider.
:type display_name: str
:param url: This url is the full route to the source resource of this graph subject.
:type url: str
:param legacy_descriptor: [Internal Use Only] The legacy descriptor is here in case you need to access old version IMS using identity descriptor.
:type legacy_descriptor: str
:param origin: The type of source provider for the origin identifier (ex:AD, AAD, MSA)
:type origin: str
:param origin_id: The unique identifier from the system of origin. Typically a sid, object id or Guid. Linking and unlinking operations can cause this value to change for a user because the user is not backed by a different provider and has a different unique id in the new provider.
:type origin_id: str
:param subject_kind: This field identifies the type of the graph subject (ex: Group, Scope, User).
:type subject_kind: str
:param domain: This represents the name of the container of origin for a graph member. (For MSA this is "Windows Live ID", for AD the name of the domain, for AAD the tenantID of the directory, for VSTS groups the ScopeId, etc)
:type domain: str
:param mail_address: The email address of record for a given graph member. This may be different than the principal name.
:type mail_address: str
:param principal_name: This is the PrincipalName of this graph member from the source provider. The source provider may change this field over time and it is not guaranteed to be immutable for the life of the graph member by VSTS.
:type principal_name: str
:param description: A short phrase to help human readers disambiguate groups with similar names
:type description: str
:param is_cross_project:
:type is_cross_project: bool
:param is_deleted:
:type is_deleted: bool
:param is_global_scope:
:type is_global_scope: bool
:param is_restricted_visible:
:type is_restricted_visible: bool
:param local_scope_id:
:type local_scope_id: str
:param scope_id:
:type scope_id: str
:param scope_name:
:type scope_name: str
:param scope_type:
:type scope_type: str
:param securing_host_id:
:type securing_host_id: str
:param special_type:
:type special_type: str
"""
_attribute_map = {
'_links': {'key': '_links', 'type': 'ReferenceLinks'},
'descriptor': {'key': 'descriptor', 'type': 'str'},
'display_name': {'key': 'displayName', 'type': 'str'},
'url': {'key': 'url', 'type': 'str'},
'legacy_descriptor': {'key': 'legacyDescriptor', 'type': 'str'},
'origin': {'key': 'origin', 'type': 'str'},
'origin_id': {'key': 'originId', 'type': 'str'},
'subject_kind': {'key': 'subjectKind', 'type': 'str'},
'domain': {'key': 'domain', 'type': 'str'},
'mail_address': {'key': 'mailAddress', 'type': 'str'},
'principal_name': {'key': 'principalName', 'type': 'str'},
'description': {'key': 'description', 'type': 'str'},
'is_cross_project': {'key': 'isCrossProject', 'type': 'bool'},
'is_deleted': {'key': 'isDeleted', 'type': 'bool'},
'is_global_scope': {'key': 'isGlobalScope', 'type': 'bool'},
'is_restricted_visible': {'key': 'isRestrictedVisible', 'type': 'bool'},
'local_scope_id': {'key': 'localScopeId', 'type': 'str'},
'scope_id': {'key': 'scopeId', 'type': 'str'},
'scope_name': {'key': 'scopeName', 'type': 'str'},
'scope_type': {'key': 'scopeType', 'type': 'str'},
'securing_host_id': {'key': 'securingHostId', 'type': 'str'},
'special_type': {'key': 'specialType', 'type': 'str'}
}
def __init__(self, _links=None, descriptor=None, display_name=None, url=None, legacy_descriptor=None, origin=None, origin_id=None, subject_kind=None, domain=None, mail_address=None, principal_name=None, description=None, is_cross_project=None, is_deleted=None, is_global_scope=None, is_restricted_visible=None, local_scope_id=None, scope_id=None, scope_name=None, scope_type=None, securing_host_id=None, special_type=None):
super(GraphGroup, self).__init__(_links=_links, descriptor=descriptor, display_name=display_name, url=url, legacy_descriptor=legacy_descriptor, origin=origin, origin_id=origin_id, subject_kind=subject_kind, domain=domain, mail_address=mail_address, principal_name=principal_name)
self.description = description
self.is_cross_project = is_cross_project
self.is_deleted = is_deleted
self.is_global_scope = is_global_scope
self.is_restricted_visible = is_restricted_visible
self.local_scope_id = local_scope_id
self.scope_id = scope_id
self.scope_name = scope_name
self.scope_type = scope_type
self.securing_host_id = securing_host_id
self.special_type = special_type
class GraphServicePrincipal(AadGraphMember):
"""
:param _links: This field contains zero or more interesting links about the graph subject. These links may be invoked to obtain additional relationships or more detailed information about this graph subject.
:type _links: :class:`ReferenceLinks <azure.devops.v7_1.microsoft._visual_studio._services._web_api.models.ReferenceLinks>`
:param descriptor: The descriptor is the primary way to reference the graph subject while the system is running. This field will uniquely identify the same graph subject across both Accounts and Organizations.
:type descriptor: str
:param display_name: This is the non-unique display name of the graph subject. To change this field, you must alter its value in the source provider.
:type display_name: str
:param url: This url is the full route to the source resource of this graph subject.
:type url: str
:param legacy_descriptor: [Internal Use Only] The legacy descriptor is here in case you need to access old version IMS using identity descriptor.
:type legacy_descriptor: str
:param origin: The type of source provider for the origin identifier (ex:AD, AAD, MSA)
:type origin: str
:param origin_id: The unique identifier from the system of origin. Typically a sid, object id or Guid. Linking and unlinking operations can cause this value to change for a user because the user is not backed by a different provider and has a different unique id in the new provider.
:type origin_id: str
:param subject_kind: This field identifies the type of the graph subject (ex: Group, Scope, User).
:type subject_kind: str
:param domain: This represents the name of the container of origin for a graph member. (For MSA this is "Windows Live ID", for AD the name of the domain, for AAD the tenantID of the directory, for VSTS groups the ScopeId, etc)
:type domain: str
:param mail_address: The email address of record for a given graph member. This may be different than the principal name.
:type mail_address: str
:param principal_name: This is the PrincipalName of this graph member from the source provider. The source provider may change this field over time and it is not guaranteed to be immutable for the life of the graph member by VSTS.
:type principal_name: str
:param directory_alias: The short, generally unique name for the user in the backing directory. For AAD users, this corresponds to the mail nickname, which is often but not necessarily similar to the part of the user's mail address before the @ sign. For GitHub users, this corresponds to the GitHub user handle.
:type directory_alias: str
:param is_deleted_in_origin: When true, the group has been deleted in the identity provider
:type is_deleted_in_origin: bool
:param metadata_update_date:
:type metadata_update_date: datetime
:param meta_type: The meta type of the user in the origin, such as "member", "guest", etc. See UserMetaType for the set of possible values.
:type meta_type: str
:param application_id:
:type application_id: str
"""
_attribute_map = {
'_links': {'key': '_links', 'type': 'ReferenceLinks'},
'descriptor': {'key': 'descriptor', 'type': 'str'},
'display_name': {'key': 'displayName', 'type': 'str'},
'url': {'key': 'url', 'type': 'str'},
'legacy_descriptor': {'key': 'legacyDescriptor', 'type': 'str'},
'origin': {'key': 'origin', 'type': 'str'},
'origin_id': {'key': 'originId', 'type': 'str'},
'subject_kind': {'key': 'subjectKind', 'type': 'str'},
'domain': {'key': 'domain', 'type': 'str'},
'mail_address': {'key': 'mailAddress', 'type': 'str'},
'principal_name': {'key': 'principalName', 'type': 'str'},
'directory_alias': {'key': 'directoryAlias', 'type': 'str'},
'is_deleted_in_origin': {'key': 'isDeletedInOrigin', 'type': 'bool'},
'metadata_update_date': {'key': 'metadataUpdateDate', 'type': 'iso-8601'},
'meta_type': {'key': 'metaType', 'type': 'str'},
'application_id': {'key': 'applicationId', 'type': 'str'}
}
def __init__(self, _links=None, descriptor=None, display_name=None, url=None, legacy_descriptor=None, origin=None, origin_id=None, subject_kind=None, domain=None, mail_address=None, principal_name=None, directory_alias=None, is_deleted_in_origin=None, metadata_update_date=None, meta_type=None, application_id=None):
super(GraphServicePrincipal, self).__init__(_links=_links, descriptor=descriptor, display_name=display_name, url=url, legacy_descriptor=legacy_descriptor, origin=origin, origin_id=origin_id, subject_kind=subject_kind, domain=domain, mail_address=mail_address, principal_name=principal_name, directory_alias=directory_alias, is_deleted_in_origin=is_deleted_in_origin, metadata_update_date=metadata_update_date, meta_type=meta_type)
self.application_id = application_id
class GraphUser(AadGraphMember):
"""
:param _links: This field contains zero or more interesting links about the graph subject. These links may be invoked to obtain additional relationships or more detailed information about this graph subject.
:type _links: :class:`ReferenceLinks <azure.devops.v7_1.microsoft._visual_studio._services._web_api.models.ReferenceLinks>`
:param descriptor: The descriptor is the primary way to reference the graph subject while the system is running. This field will uniquely identify the same graph subject across both Accounts and Organizations.
:type descriptor: str
:param display_name: This is the non-unique display name of the graph subject. To change this field, you must alter its value in the source provider.
:type display_name: str
:param url: This url is the full route to the source resource of this graph subject.
:type url: str
:param legacy_descriptor: [Internal Use Only] The legacy descriptor is here in case you need to access old version IMS using identity descriptor.
:type legacy_descriptor: str
:param origin: The type of source provider for the origin identifier (ex:AD, AAD, MSA)
:type origin: str
:param origin_id: The unique identifier from the system of origin. Typically a sid, object id or Guid. Linking and unlinking operations can cause this value to change for a user because the user is not backed by a different provider and has a different unique id in the new provider.
:type origin_id: str
:param subject_kind: This field identifies the type of the graph subject (ex: Group, Scope, User).
:type subject_kind: str
:param domain: This represents the name of the container of origin for a graph member. (For MSA this is "Windows Live ID", for AD the name of the domain, for AAD the tenantID of the directory, for VSTS groups the ScopeId, etc)
:type domain: str
:param mail_address: The email address of record for a given graph member. This may be different than the principal name.
:type mail_address: str
:param principal_name: This is the PrincipalName of this graph member from the source provider. The source provider may change this field over time and it is not guaranteed to be immutable for the life of the graph member by VSTS.
:type principal_name: str
:param directory_alias: The short, generally unique name for the user in the backing directory. For AAD users, this corresponds to the mail nickname, which is often but not necessarily similar to the part of the user's mail address before the @ sign. For GitHub users, this corresponds to the GitHub user handle.
:type directory_alias: str
:param is_deleted_in_origin: When true, the group has been deleted in the identity provider
:type is_deleted_in_origin: bool
:param metadata_update_date:
:type metadata_update_date: datetime
:param meta_type: The meta type of the user in the origin, such as "member", "guest", etc. See UserMetaType for the set of possible values.
:type meta_type: str
"""
_attribute_map = {
'_links': {'key': '_links', 'type': 'ReferenceLinks'},
'descriptor': {'key': 'descriptor', 'type': 'str'},
'display_name': {'key': 'displayName', 'type': 'str'},
'url': {'key': 'url', 'type': 'str'},
'legacy_descriptor': {'key': 'legacyDescriptor', 'type': 'str'},
'origin': {'key': 'origin', 'type': 'str'},
'origin_id': {'key': 'originId', 'type': 'str'},
'subject_kind': {'key': 'subjectKind', 'type': 'str'},
'domain': {'key': 'domain', 'type': 'str'},
'mail_address': {'key': 'mailAddress', 'type': 'str'},
'principal_name': {'key': 'principalName', 'type': 'str'},
'directory_alias': {'key': 'directoryAlias', 'type': 'str'},
'is_deleted_in_origin': {'key': 'isDeletedInOrigin', 'type': 'bool'},
'metadata_update_date': {'key': 'metadataUpdateDate', 'type': 'iso-8601'},
'meta_type': {'key': 'metaType', 'type': 'str'},
}
def __init__(self, _links=None, descriptor=None, display_name=None, url=None, legacy_descriptor=None, origin=None, origin_id=None, subject_kind=None, domain=None, mail_address=None, principal_name=None, directory_alias=None, is_deleted_in_origin=None, metadata_update_date=None, meta_type=None):
super(GraphUser, self).__init__(_links=_links, descriptor=descriptor, display_name=display_name, url=url, legacy_descriptor=legacy_descriptor, origin=origin, origin_id=origin_id, subject_kind=subject_kind, domain=domain, mail_address=mail_address, principal_name=principal_name, directory_alias=directory_alias, is_deleted_in_origin=is_deleted_in_origin, metadata_update_date=metadata_update_date, meta_type=meta_type)
__all__ = [
'AccessLevel',
'BaseOperationResult',
'EntitlementBase',
'EntitlementOperationResultBase',
'Extension',
'GraphSubjectBase',
'Group',
'GroupEntitlement',
'GroupOperationResult',
'GroupOption',
'JsonPatchOperation',
'MemberEntitlement2',
'MemberEntitlement2OperationResult',
'MemberEntitlement2ResponseBase',
'MemberEntitlementsResponseBase',
'OperationReference',
'OperationResult',
'PagedList',
'ProjectEntitlement',
'ProjectRef',
'ReferenceLinks',
'ServicePrincipalEntitlement',
'ServicePrincipalEntitlementOperationReference',
'ServicePrincipalEntitlementOperationResult',
'ServicePrincipalEntitlementsResponseBase',
'SummaryData',
'TeamRef',
'UserEntitlement',
'UserEntitlementOperationReference',
'UserEntitlementOperationResult',
'UserEntitlementsResponseBase',
'UsersSummary',
'ExtensionSummaryData',
'GraphSubject',
'GroupEntitlementOperationReference',
'LicenseSummaryData',
'MemberEntitlement',
'MemberEntitlement2OperationReference',
'MemberEntitlement2PatchResponse',
'MemberEntitlement2PostResponse',
'MemberEntitlementOperationReference',
'MemberEntitlementsPatchResponse',
'MemberEntitlementsPostResponse',
'PagedGraphMemberList',
'ServicePrincipalEntitlementsPatchResponse',
'ServicePrincipalEntitlementsPostResponse',
'UserEntitlementsPatchResponse',
'UserEntitlementsPostResponse',
'GraphMember',
'AadGraphMember',
'GraphGroup',
'GraphServicePrincipal',
'GraphUser',
]
|
azure-devops-python-api/azure-devops/azure/devops/v7_1/member_entitlement_management/models.py/0
|
{
"file_path": "azure-devops-python-api/azure-devops/azure/devops/v7_1/member_entitlement_management/models.py",
"repo_id": "azure-devops-python-api",
"token_count": 31356
}
| 364 |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
# Generated file, DO NOT EDIT
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------------------------
from .models import *
from .pipelines_client import PipelinesClient
__all__ = [
'Artifact',
'BuildResourceParameters',
'Container',
'ContainerResource',
'ContainerResourceParameters',
'CreatePipelineConfigurationParameters',
'CreatePipelineParameters',
'Log',
'LogCollection',
'PackageResourceParameters',
'Pipeline',
'PipelineBase',
'PipelineConfiguration',
'PipelineReference',
'PipelineResource',
'PipelineResourceParameters',
'PreviewRun',
'ReferenceLinks',
'Repository',
'RepositoryResource',
'RepositoryResourceParameters',
'Run',
'RunPipelineParameters',
'RunReference',
'RunResources',
'RunResourcesParameters',
'SignalRConnection',
'SignedUrl',
'Variable',
'PipelinesClient'
]
|
azure-devops-python-api/azure-devops/azure/devops/v7_1/pipelines/__init__.py/0
|
{
"file_path": "azure-devops-python-api/azure-devops/azure/devops/v7_1/pipelines/__init__.py",
"repo_id": "azure-devops-python-api",
"token_count": 376
}
| 365 |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
# Generated file, DO NOT EDIT
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------------------------
from msrest.serialization import Model
class CodeChangeTrendItem(Model):
"""
:param time:
:type time: datetime
:param value:
:type value: int
"""
_attribute_map = {
'time': {'key': 'time', 'type': 'iso-8601'},
'value': {'key': 'value', 'type': 'int'}
}
def __init__(self, time=None, value=None):
super(CodeChangeTrendItem, self).__init__()
self.time = time
self.value = value
class LanguageMetricsSecuredObject(Model):
"""
:param namespace_id:
:type namespace_id: str
:param project_id:
:type project_id: str
:param required_permissions:
:type required_permissions: int
"""
_attribute_map = {
'namespace_id': {'key': 'namespaceId', 'type': 'str'},
'project_id': {'key': 'projectId', 'type': 'str'},
'required_permissions': {'key': 'requiredPermissions', 'type': 'int'}
}
def __init__(self, namespace_id=None, project_id=None, required_permissions=None):
super(LanguageMetricsSecuredObject, self).__init__()
self.namespace_id = namespace_id
self.project_id = project_id
self.required_permissions = required_permissions
class LanguageStatistics(LanguageMetricsSecuredObject):
"""
:param namespace_id:
:type namespace_id: str
:param project_id:
:type project_id: str
:param required_permissions:
:type required_permissions: int
:param bytes:
:type bytes: long
:param files:
:type files: int
:param files_percentage:
:type files_percentage: float
:param language_percentage:
:type language_percentage: float
:param name:
:type name: str
"""
_attribute_map = {
'namespace_id': {'key': 'namespaceId', 'type': 'str'},
'project_id': {'key': 'projectId', 'type': 'str'},
'required_permissions': {'key': 'requiredPermissions', 'type': 'int'},
'bytes': {'key': 'bytes', 'type': 'long'},
'files': {'key': 'files', 'type': 'int'},
'files_percentage': {'key': 'filesPercentage', 'type': 'float'},
'language_percentage': {'key': 'languagePercentage', 'type': 'float'},
'name': {'key': 'name', 'type': 'str'}
}
def __init__(self, namespace_id=None, project_id=None, required_permissions=None, bytes=None, files=None, files_percentage=None, language_percentage=None, name=None):
super(LanguageStatistics, self).__init__(namespace_id=namespace_id, project_id=project_id, required_permissions=required_permissions)
self.bytes = bytes
self.files = files
self.files_percentage = files_percentage
self.language_percentage = language_percentage
self.name = name
class ProjectActivityMetrics(Model):
"""
:param authors_count:
:type authors_count: int
:param code_changes_count:
:type code_changes_count: int
:param code_changes_trend:
:type code_changes_trend: list of :class:`CodeChangeTrendItem <azure.devops.v7_1.project_analysis.models.CodeChangeTrendItem>`
:param project_id:
:type project_id: str
:param pull_requests_completed_count:
:type pull_requests_completed_count: int
:param pull_requests_created_count:
:type pull_requests_created_count: int
"""
_attribute_map = {
'authors_count': {'key': 'authorsCount', 'type': 'int'},
'code_changes_count': {'key': 'codeChangesCount', 'type': 'int'},
'code_changes_trend': {'key': 'codeChangesTrend', 'type': '[CodeChangeTrendItem]'},
'project_id': {'key': 'projectId', 'type': 'str'},
'pull_requests_completed_count': {'key': 'pullRequestsCompletedCount', 'type': 'int'},
'pull_requests_created_count': {'key': 'pullRequestsCreatedCount', 'type': 'int'}
}
def __init__(self, authors_count=None, code_changes_count=None, code_changes_trend=None, project_id=None, pull_requests_completed_count=None, pull_requests_created_count=None):
super(ProjectActivityMetrics, self).__init__()
self.authors_count = authors_count
self.code_changes_count = code_changes_count
self.code_changes_trend = code_changes_trend
self.project_id = project_id
self.pull_requests_completed_count = pull_requests_completed_count
self.pull_requests_created_count = pull_requests_created_count
class ProjectLanguageAnalytics(LanguageMetricsSecuredObject):
"""
:param namespace_id:
:type namespace_id: str
:param project_id:
:type project_id: str
:param required_permissions:
:type required_permissions: int
:param id:
:type id: str
:param language_breakdown:
:type language_breakdown: list of :class:`LanguageStatistics <azure.devops.v7_1.project_analysis.models.LanguageStatistics>`
:param repository_language_analytics:
:type repository_language_analytics: list of :class:`RepositoryLanguageAnalytics <azure.devops.v7_1.project_analysis.models.RepositoryLanguageAnalytics>`
:param result_phase:
:type result_phase: object
:param url:
:type url: str
"""
_attribute_map = {
'namespace_id': {'key': 'namespaceId', 'type': 'str'},
'project_id': {'key': 'projectId', 'type': 'str'},
'required_permissions': {'key': 'requiredPermissions', 'type': 'int'},
'id': {'key': 'id', 'type': 'str'},
'language_breakdown': {'key': 'languageBreakdown', 'type': '[LanguageStatistics]'},
'repository_language_analytics': {'key': 'repositoryLanguageAnalytics', 'type': '[RepositoryLanguageAnalytics]'},
'result_phase': {'key': 'resultPhase', 'type': 'object'},
'url': {'key': 'url', 'type': 'str'}
}
def __init__(self, namespace_id=None, project_id=None, required_permissions=None, id=None, language_breakdown=None, repository_language_analytics=None, result_phase=None, url=None):
super(ProjectLanguageAnalytics, self).__init__(namespace_id=namespace_id, project_id=project_id, required_permissions=required_permissions)
self.id = id
self.language_breakdown = language_breakdown
self.repository_language_analytics = repository_language_analytics
self.result_phase = result_phase
self.url = url
class RepositoryActivityMetrics(Model):
"""
:param code_changes_count:
:type code_changes_count: int
:param code_changes_trend:
:type code_changes_trend: list of :class:`CodeChangeTrendItem <azure.devops.v7_1.project_analysis.models.CodeChangeTrendItem>`
:param repository_id:
:type repository_id: str
"""
_attribute_map = {
'code_changes_count': {'key': 'codeChangesCount', 'type': 'int'},
'code_changes_trend': {'key': 'codeChangesTrend', 'type': '[CodeChangeTrendItem]'},
'repository_id': {'key': 'repositoryId', 'type': 'str'}
}
def __init__(self, code_changes_count=None, code_changes_trend=None, repository_id=None):
super(RepositoryActivityMetrics, self).__init__()
self.code_changes_count = code_changes_count
self.code_changes_trend = code_changes_trend
self.repository_id = repository_id
class RepositoryLanguageAnalytics(LanguageMetricsSecuredObject):
"""
:param namespace_id:
:type namespace_id: str
:param project_id:
:type project_id: str
:param required_permissions:
:type required_permissions: int
:param id:
:type id: str
:param language_breakdown:
:type language_breakdown: list of :class:`LanguageStatistics <azure.devops.v7_1.project_analysis.models.LanguageStatistics>`
:param name:
:type name: str
:param result_phase:
:type result_phase: object
:param updated_time:
:type updated_time: datetime
"""
_attribute_map = {
'namespace_id': {'key': 'namespaceId', 'type': 'str'},
'project_id': {'key': 'projectId', 'type': 'str'},
'required_permissions': {'key': 'requiredPermissions', 'type': 'int'},
'id': {'key': 'id', 'type': 'str'},
'language_breakdown': {'key': 'languageBreakdown', 'type': '[LanguageStatistics]'},
'name': {'key': 'name', 'type': 'str'},
'result_phase': {'key': 'resultPhase', 'type': 'object'},
'updated_time': {'key': 'updatedTime', 'type': 'iso-8601'}
}
def __init__(self, namespace_id=None, project_id=None, required_permissions=None, id=None, language_breakdown=None, name=None, result_phase=None, updated_time=None):
super(RepositoryLanguageAnalytics, self).__init__(namespace_id=namespace_id, project_id=project_id, required_permissions=required_permissions)
self.id = id
self.language_breakdown = language_breakdown
self.name = name
self.result_phase = result_phase
self.updated_time = updated_time
__all__ = [
'CodeChangeTrendItem',
'LanguageMetricsSecuredObject',
'LanguageStatistics',
'ProjectActivityMetrics',
'ProjectLanguageAnalytics',
'RepositoryActivityMetrics',
'RepositoryLanguageAnalytics',
]
|
azure-devops-python-api/azure-devops/azure/devops/v7_1/project_analysis/models.py/0
|
{
"file_path": "azure-devops-python-api/azure-devops/azure/devops/v7_1/project_analysis/models.py",
"repo_id": "azure-devops-python-api",
"token_count": 3613
}
| 366 |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
# Generated file, DO NOT EDIT
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------------------------
from msrest.serialization import Model
class Issue(Model):
"""
An issue (error, warning) associated with a pipeline run.
:param category: The category of the issue. <br />Example: Code - refers to compilation errors <br />Example: General - refers to generic errors
:type category: str
:param data: A dictionary containing details about the issue.
:type data: dict
:param message: A description of issue.
:type message: str
:param type: The type (error, warning) of the issue.
:type type: object
"""
_attribute_map = {
'category': {'key': 'category', 'type': 'str'},
'data': {'key': 'data', 'type': '{str}'},
'message': {'key': 'message', 'type': 'str'},
'type': {'key': 'type', 'type': 'object'}
}
def __init__(self, category=None, data=None, message=None, type=None):
super(Issue, self).__init__()
self.category = category
self.data = data
self.message = message
self.type = type
class JobEvent(Model):
"""
A pipeline job event to be processed by the execution plan.
:param job_id: The ID of the pipeline job affected by the event.
:type job_id: str
:param name: The name of the pipeline job event.
:type name: str
"""
_attribute_map = {
'job_id': {'key': 'jobId', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'}
}
def __init__(self, job_id=None, name=None):
super(JobEvent, self).__init__()
self.job_id = job_id
self.name = name
class JobOption(Model):
"""
Represents an option that may affect the way an agent runs the job.
:param data:
:type data: dict
:param id: Gets the id of the option.
:type id: str
"""
_attribute_map = {
'data': {'key': 'data', 'type': '{str}'},
'id': {'key': 'id', 'type': 'str'}
}
def __init__(self, data=None, id=None):
super(JobOption, self).__init__()
self.data = data
self.id = id
class MaskHint(Model):
"""
:param type:
:type type: object
:param value:
:type value: str
"""
_attribute_map = {
'type': {'key': 'type', 'type': 'object'},
'value': {'key': 'value', 'type': 'str'}
}
def __init__(self, type=None, value=None):
super(MaskHint, self).__init__()
self.type = type
self.value = value
class PlanEnvironment(Model):
"""
:param mask:
:type mask: list of :class:`MaskHint <azure.devops.v7_1.task.models.MaskHint>`
:param options:
:type options: dict
:param variables:
:type variables: dict
"""
_attribute_map = {
'mask': {'key': 'mask', 'type': '[MaskHint]'},
'options': {'key': 'options', 'type': '{JobOption}'},
'variables': {'key': 'variables', 'type': '{str}'}
}
def __init__(self, mask=None, options=None, variables=None):
super(PlanEnvironment, self).__init__()
self.mask = mask
self.options = options
self.variables = variables
class ProjectReference(Model):
"""
:param id:
:type id: str
:param name:
:type name: str
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'}
}
def __init__(self, id=None, name=None):
super(ProjectReference, self).__init__()
self.id = id
self.name = name
class ReferenceLinks(Model):
"""
The class to represent a collection of REST reference links.
:param links: The readonly view of the links. Because Reference links are readonly, we only want to expose them as read only.
:type links: dict
"""
_attribute_map = {
'links': {'key': 'links', 'type': '{object}'}
}
def __init__(self, links=None):
super(ReferenceLinks, self).__init__()
self.links = links
class TaskAgentJob(Model):
"""
:param container:
:type container: str
:param id:
:type id: str
:param name:
:type name: str
:param sidecar_containers:
:type sidecar_containers: dict
:param steps:
:type steps: list of :class:`TaskAgentJobStep <azure.devops.v7_1.task.models.TaskAgentJobStep>`
:param variables:
:type variables: list of :class:`TaskAgentJobVariable <azure.devops.v7_1.task.models.TaskAgentJobVariable>`
"""
_attribute_map = {
'container': {'key': 'container', 'type': 'str'},
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'sidecar_containers': {'key': 'sidecarContainers', 'type': '{str}'},
'steps': {'key': 'steps', 'type': '[TaskAgentJobStep]'},
'variables': {'key': 'variables', 'type': '[TaskAgentJobVariable]'}
}
def __init__(self, container=None, id=None, name=None, sidecar_containers=None, steps=None, variables=None):
super(TaskAgentJob, self).__init__()
self.container = container
self.id = id
self.name = name
self.sidecar_containers = sidecar_containers
self.steps = steps
self.variables = variables
class TaskAgentJobStep(Model):
"""
:param condition:
:type condition: str
:param continue_on_error:
:type continue_on_error: bool
:param enabled:
:type enabled: bool
:param env:
:type env: dict
:param id:
:type id: str
:param inputs:
:type inputs: dict
:param name:
:type name: str
:param retry_count_on_task_failure:
:type retry_count_on_task_failure: int
:param task:
:type task: :class:`TaskAgentJobTask <azure.devops.v7_1.task.models.TaskAgentJobTask>`
:param timeout_in_minutes:
:type timeout_in_minutes: int
:param type:
:type type: object
"""
_attribute_map = {
'condition': {'key': 'condition', 'type': 'str'},
'continue_on_error': {'key': 'continueOnError', 'type': 'bool'},
'enabled': {'key': 'enabled', 'type': 'bool'},
'env': {'key': 'env', 'type': '{str}'},
'id': {'key': 'id', 'type': 'str'},
'inputs': {'key': 'inputs', 'type': '{str}'},
'name': {'key': 'name', 'type': 'str'},
'retry_count_on_task_failure': {'key': 'retryCountOnTaskFailure', 'type': 'int'},
'task': {'key': 'task', 'type': 'TaskAgentJobTask'},
'timeout_in_minutes': {'key': 'timeoutInMinutes', 'type': 'int'},
'type': {'key': 'type', 'type': 'object'}
}
def __init__(self, condition=None, continue_on_error=None, enabled=None, env=None, id=None, inputs=None, name=None, retry_count_on_task_failure=None, task=None, timeout_in_minutes=None, type=None):
super(TaskAgentJobStep, self).__init__()
self.condition = condition
self.continue_on_error = continue_on_error
self.enabled = enabled
self.env = env
self.id = id
self.inputs = inputs
self.name = name
self.retry_count_on_task_failure = retry_count_on_task_failure
self.task = task
self.timeout_in_minutes = timeout_in_minutes
self.type = type
class TaskAgentJobTask(Model):
"""
:param id:
:type id: str
:param name:
:type name: str
:param version:
:type version: str
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'version': {'key': 'version', 'type': 'str'}
}
def __init__(self, id=None, name=None, version=None):
super(TaskAgentJobTask, self).__init__()
self.id = id
self.name = name
self.version = version
class TaskAgentJobVariable(Model):
"""
:param name:
:type name: str
:param secret:
:type secret: bool
:param value:
:type value: str
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'secret': {'key': 'secret', 'type': 'bool'},
'value': {'key': 'value', 'type': 'str'}
}
def __init__(self, name=None, secret=None, value=None):
super(TaskAgentJobVariable, self).__init__()
self.name = name
self.secret = secret
self.value = value
class TaskAttachment(Model):
"""
:param _links:
:type _links: :class:`ReferenceLinks <azure.devops.v7_1.task.models.ReferenceLinks>`
:param created_on:
:type created_on: datetime
:param last_changed_by:
:type last_changed_by: str
:param last_changed_on:
:type last_changed_on: datetime
:param name:
:type name: str
:param record_id:
:type record_id: str
:param timeline_id:
:type timeline_id: str
:param type:
:type type: str
"""
_attribute_map = {
'_links': {'key': '_links', 'type': 'ReferenceLinks'},
'created_on': {'key': 'createdOn', 'type': 'iso-8601'},
'last_changed_by': {'key': 'lastChangedBy', 'type': 'str'},
'last_changed_on': {'key': 'lastChangedOn', 'type': 'iso-8601'},
'name': {'key': 'name', 'type': 'str'},
'record_id': {'key': 'recordId', 'type': 'str'},
'timeline_id': {'key': 'timelineId', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'}
}
def __init__(self, _links=None, created_on=None, last_changed_by=None, last_changed_on=None, name=None, record_id=None, timeline_id=None, type=None):
super(TaskAttachment, self).__init__()
self._links = _links
self.created_on = created_on
self.last_changed_by = last_changed_by
self.last_changed_on = last_changed_on
self.name = name
self.record_id = record_id
self.timeline_id = timeline_id
self.type = type
class TaskHubOidcToken(Model):
"""
:param oidc_token:
:type oidc_token: str
"""
_attribute_map = {
'oidc_token': {'key': 'oidcToken', 'type': 'str'}
}
def __init__(self, oidc_token=None):
super(TaskHubOidcToken, self).__init__()
self.oidc_token = oidc_token
class TaskLogReference(Model):
"""
A reference to a task log. This class contains information about the output printed to the timeline record's logs console during pipeline run.
:param id: The ID of the task log.
:type id: int
:param location: The REST URL of the task log.
:type location: str
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'int'},
'location': {'key': 'location', 'type': 'str'}
}
def __init__(self, id=None, location=None):
super(TaskLogReference, self).__init__()
self.id = id
self.location = location
class TaskOrchestrationItem(Model):
"""
:param item_type:
:type item_type: object
"""
_attribute_map = {
'item_type': {'key': 'itemType', 'type': 'object'}
}
def __init__(self, item_type=None):
super(TaskOrchestrationItem, self).__init__()
self.item_type = item_type
class TaskOrchestrationOwner(Model):
"""
:param _links:
:type _links: :class:`ReferenceLinks <azure.devops.v7_1.task.models.ReferenceLinks>`
:param id:
:type id: int
:param name:
:type name: str
"""
_attribute_map = {
'_links': {'key': '_links', 'type': 'ReferenceLinks'},
'id': {'key': 'id', 'type': 'int'},
'name': {'key': 'name', 'type': 'str'}
}
def __init__(self, _links=None, id=None, name=None):
super(TaskOrchestrationOwner, self).__init__()
self._links = _links
self.id = id
self.name = name
class TaskOrchestrationPlanGroupsQueueMetrics(Model):
"""
:param count:
:type count: int
:param status:
:type status: object
"""
_attribute_map = {
'count': {'key': 'count', 'type': 'int'},
'status': {'key': 'status', 'type': 'object'}
}
def __init__(self, count=None, status=None):
super(TaskOrchestrationPlanGroupsQueueMetrics, self).__init__()
self.count = count
self.status = status
class TaskOrchestrationPlanReference(Model):
"""
:param artifact_location:
:type artifact_location: str
:param artifact_uri:
:type artifact_uri: str
:param definition:
:type definition: :class:`TaskOrchestrationOwner <azure.devops.v7_1.task.models.TaskOrchestrationOwner>`
:param owner:
:type owner: :class:`TaskOrchestrationOwner <azure.devops.v7_1.task.models.TaskOrchestrationOwner>`
:param plan_group:
:type plan_group: str
:param plan_id:
:type plan_id: str
:param plan_type:
:type plan_type: str
:param scope_identifier:
:type scope_identifier: str
:param version:
:type version: int
"""
_attribute_map = {
'artifact_location': {'key': 'artifactLocation', 'type': 'str'},
'artifact_uri': {'key': 'artifactUri', 'type': 'str'},
'definition': {'key': 'definition', 'type': 'TaskOrchestrationOwner'},
'owner': {'key': 'owner', 'type': 'TaskOrchestrationOwner'},
'plan_group': {'key': 'planGroup', 'type': 'str'},
'plan_id': {'key': 'planId', 'type': 'str'},
'plan_type': {'key': 'planType', 'type': 'str'},
'scope_identifier': {'key': 'scopeIdentifier', 'type': 'str'},
'version': {'key': 'version', 'type': 'int'}
}
def __init__(self, artifact_location=None, artifact_uri=None, definition=None, owner=None, plan_group=None, plan_id=None, plan_type=None, scope_identifier=None, version=None):
super(TaskOrchestrationPlanReference, self).__init__()
self.artifact_location = artifact_location
self.artifact_uri = artifact_uri
self.definition = definition
self.owner = owner
self.plan_group = plan_group
self.plan_id = plan_id
self.plan_type = plan_type
self.scope_identifier = scope_identifier
self.version = version
class TaskOrchestrationQueuedPlan(Model):
"""
:param assign_time:
:type assign_time: datetime
:param definition:
:type definition: :class:`TaskOrchestrationOwner <azure.devops.v7_1.task.models.TaskOrchestrationOwner>`
:param owner:
:type owner: :class:`TaskOrchestrationOwner <azure.devops.v7_1.task.models.TaskOrchestrationOwner>`
:param plan_group:
:type plan_group: str
:param plan_id:
:type plan_id: str
:param pool_id:
:type pool_id: int
:param queue_position:
:type queue_position: int
:param queue_time:
:type queue_time: datetime
:param scope_identifier:
:type scope_identifier: str
"""
_attribute_map = {
'assign_time': {'key': 'assignTime', 'type': 'iso-8601'},
'definition': {'key': 'definition', 'type': 'TaskOrchestrationOwner'},
'owner': {'key': 'owner', 'type': 'TaskOrchestrationOwner'},
'plan_group': {'key': 'planGroup', 'type': 'str'},
'plan_id': {'key': 'planId', 'type': 'str'},
'pool_id': {'key': 'poolId', 'type': 'int'},
'queue_position': {'key': 'queuePosition', 'type': 'int'},
'queue_time': {'key': 'queueTime', 'type': 'iso-8601'},
'scope_identifier': {'key': 'scopeIdentifier', 'type': 'str'}
}
def __init__(self, assign_time=None, definition=None, owner=None, plan_group=None, plan_id=None, pool_id=None, queue_position=None, queue_time=None, scope_identifier=None):
super(TaskOrchestrationQueuedPlan, self).__init__()
self.assign_time = assign_time
self.definition = definition
self.owner = owner
self.plan_group = plan_group
self.plan_id = plan_id
self.pool_id = pool_id
self.queue_position = queue_position
self.queue_time = queue_time
self.scope_identifier = scope_identifier
class TaskOrchestrationQueuedPlanGroup(Model):
"""
:param definition:
:type definition: :class:`TaskOrchestrationOwner <azure.devops.v7_1.task.models.TaskOrchestrationOwner>`
:param owner:
:type owner: :class:`TaskOrchestrationOwner <azure.devops.v7_1.task.models.TaskOrchestrationOwner>`
:param plan_group:
:type plan_group: str
:param plans:
:type plans: list of :class:`TaskOrchestrationQueuedPlan <azure.devops.v7_1.task.models.TaskOrchestrationQueuedPlan>`
:param project:
:type project: :class:`ProjectReference <azure.devops.v7_1.task.models.ProjectReference>`
:param queue_position:
:type queue_position: int
"""
_attribute_map = {
'definition': {'key': 'definition', 'type': 'TaskOrchestrationOwner'},
'owner': {'key': 'owner', 'type': 'TaskOrchestrationOwner'},
'plan_group': {'key': 'planGroup', 'type': 'str'},
'plans': {'key': 'plans', 'type': '[TaskOrchestrationQueuedPlan]'},
'project': {'key': 'project', 'type': 'ProjectReference'},
'queue_position': {'key': 'queuePosition', 'type': 'int'}
}
def __init__(self, definition=None, owner=None, plan_group=None, plans=None, project=None, queue_position=None):
super(TaskOrchestrationQueuedPlanGroup, self).__init__()
self.definition = definition
self.owner = owner
self.plan_group = plan_group
self.plans = plans
self.project = project
self.queue_position = queue_position
class TaskReference(Model):
"""
A reference to a task.
:param id: The ID of the task definition. Corresponds to the id value of task.json file. <br />Example: CmdLineV2 { "id": "D9BAFED4-0B18-4F58-968D-86655B4D2CE9" }
:type id: str
:param inputs: A dictionary of inputs specific to a task definition. Corresponds to inputs value of task.json file.
:type inputs: dict
:param name: The name of the task definition. Corresponds to the name value of task.json file. <br />Example: CmdLineV2 { "name": "CmdLine" }
:type name: str
:param version: The version of the task definition. Corresponds to the version value of task.json file. <br />Example: CmdLineV2 { "version": { "Major": 2, "Minor": 212, "Patch": 0 } }
:type version: str
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'inputs': {'key': 'inputs', 'type': '{str}'},
'name': {'key': 'name', 'type': 'str'},
'version': {'key': 'version', 'type': 'str'}
}
def __init__(self, id=None, inputs=None, name=None, version=None):
super(TaskReference, self).__init__()
self.id = id
self.inputs = inputs
self.name = name
self.version = version
class TimelineAttempt(Model):
"""
An attempt to update a TimelineRecord.
:param attempt: The attempt of the record.
:type attempt: int
:param identifier: The unique identifier for the record.
:type identifier: str
:param record_id: The record identifier located within the specified timeline.
:type record_id: str
:param timeline_id: The timeline identifier which owns the record representing this attempt.
:type timeline_id: str
"""
_attribute_map = {
'attempt': {'key': 'attempt', 'type': 'int'},
'identifier': {'key': 'identifier', 'type': 'str'},
'record_id': {'key': 'recordId', 'type': 'str'},
'timeline_id': {'key': 'timelineId', 'type': 'str'}
}
def __init__(self, attempt=None, identifier=None, record_id=None, timeline_id=None):
super(TimelineAttempt, self).__init__()
self.attempt = attempt
self.identifier = identifier
self.record_id = record_id
self.timeline_id = timeline_id
class TimelineRecord(Model):
"""
Detailed information about the execution of different operations during pipeline run.
:param agent_specification: The specification of an agent running a pipeline job, in binary format. Applicable when record is of type Job. <br />Example: { "VMImage" : "windows-2019" }
:type agent_specification: :class:`object <azure.devops.v7_1.task.models.object>`
:param attempt: The number of record attempts.
:type attempt: int
:param current_operation: A string that indicates the current operation.
:type current_operation: str
:param details: A reference to a sub-timeline.
:type details: :class:`TimelineReference <azure.devops.v7_1.task.models.TimelineReference>`
:param error_count: The number of errors produced by this operation.
:type error_count: int
:param finish_time: The finish time of the record.
:type finish_time: datetime
:param change_id: The ID connecting all records updated at the same time. This value is taken from timeline's ChangeId.
:type change_id: int
:param id: The ID of the record.
:type id: str
:param identifier: String identifier that is consistent across attempts.
:type identifier: str
:param issues: The list of issues produced by this operation.
:type issues: list of :class:`Issue <azure.devops.v7_1.task.models.Issue>`
:param last_modified: The time the record was last modified.
:type last_modified: datetime
:param location: The REST URL of the record.
:type location: str
:param log: A reference to the log produced by this operation.
:type log: :class:`TaskLogReference <azure.devops.v7_1.task.models.TaskLogReference>`
:param name: The name of the record.
:type name: str
:param order: An ordinal value relative to other records within the timeline.
:type order: int
:param parent_id: The ID of the record's parent. <br />Example: Stage is a parent of a Phase, Phase is a parent of a Job, Job is a parent of a Task.
:type parent_id: str
:param percent_complete: The percentage of record completion.
:type percent_complete: int
:param previous_attempts: The previous record attempts.
:type previous_attempts: list of :class:`TimelineAttempt <azure.devops.v7_1.task.models.TimelineAttempt>`
:param queue_id: The ID of the queue which connects projects to agent pools on which the operation ran on. Applicable when record is of type Job.
:type queue_id: int
:param ref_name: Name of the referenced record.
:type ref_name: str
:param result: The result of the record.
:type result: object
:param result_code: Evaluation of predefined conditions upon completion of record's operation. <br />Example: Evaluating `succeeded()`, Result = True <br />Example: Evaluating `and(succeeded(), eq(variables['system.debug'], False))`, Result = False
:type result_code: str
:param start_time: The start time of the record.
:type start_time: datetime
:param state: The state of the record.
:type state: object
:param task: A reference to the task. Applicable when record is of type Task.
:type task: :class:`TaskReference <azure.devops.v7_1.task.models.TaskReference>`
:param type: The type of operation being tracked by the record. <br />Example: Stage, Phase, Job, Task...
:type type: str
:param variables: The variables of the record.
:type variables: dict
:param warning_count: The number of warnings produced by this operation.
:type warning_count: int
:param worker_name: The name of the agent running the operation. Applicable when record is of type Job.
:type worker_name: str
"""
_attribute_map = {
'agent_specification': {'key': 'agentSpecification', 'type': 'object'},
'attempt': {'key': 'attempt', 'type': 'int'},
'current_operation': {'key': 'currentOperation', 'type': 'str'},
'details': {'key': 'details', 'type': 'TimelineReference'},
'error_count': {'key': 'errorCount', 'type': 'int'},
'finish_time': {'key': 'finishTime', 'type': 'iso-8601'},
'change_id': {'key': 'changeId', 'type': 'int'},
'id': {'key': 'id', 'type': 'str'},
'identifier': {'key': 'identifier', 'type': 'str'},
'issues': {'key': 'issues', 'type': '[Issue]'},
'last_modified': {'key': 'lastModified', 'type': 'iso-8601'},
'location': {'key': 'location', 'type': 'str'},
'log': {'key': 'log', 'type': 'TaskLogReference'},
'name': {'key': 'name', 'type': 'str'},
'order': {'key': 'order', 'type': 'int'},
'parent_id': {'key': 'parentId', 'type': 'str'},
'percent_complete': {'key': 'percentComplete', 'type': 'int'},
'previous_attempts': {'key': 'previousAttempts', 'type': '[TimelineAttempt]'},
'queue_id': {'key': 'queueId', 'type': 'int'},
'ref_name': {'key': 'refName', 'type': 'str'},
'result': {'key': 'result', 'type': 'object'},
'result_code': {'key': 'resultCode', 'type': 'str'},
'start_time': {'key': 'startTime', 'type': 'iso-8601'},
'state': {'key': 'state', 'type': 'object'},
'task': {'key': 'task', 'type': 'TaskReference'},
'type': {'key': 'type', 'type': 'str'},
'variables': {'key': 'variables', 'type': '{VariableValue}'},
'warning_count': {'key': 'warningCount', 'type': 'int'},
'worker_name': {'key': 'workerName', 'type': 'str'}
}
def __init__(self, agent_specification=None, attempt=None, current_operation=None, details=None, error_count=None, finish_time=None, change_id=None, id=None, identifier=None, issues=None, last_modified=None, location=None, log=None, name=None, order=None, parent_id=None, percent_complete=None, previous_attempts=None, queue_id=None, ref_name=None, result=None, result_code=None, start_time=None, state=None, task=None, type=None, variables=None, warning_count=None, worker_name=None):
super(TimelineRecord, self).__init__()
self.agent_specification = agent_specification
self.attempt = attempt
self.current_operation = current_operation
self.details = details
self.error_count = error_count
self.finish_time = finish_time
self.change_id = change_id
self.id = id
self.identifier = identifier
self.issues = issues
self.last_modified = last_modified
self.location = location
self.log = log
self.name = name
self.order = order
self.parent_id = parent_id
self.percent_complete = percent_complete
self.previous_attempts = previous_attempts
self.queue_id = queue_id
self.ref_name = ref_name
self.result = result
self.result_code = result_code
self.start_time = start_time
self.state = state
self.task = task
self.type = type
self.variables = variables
self.warning_count = warning_count
self.worker_name = worker_name
class TimelineRecordFeedLinesWrapper(Model):
"""
:param count:
:type count: int
:param end_line:
:type end_line: long
:param start_line:
:type start_line: long
:param step_id:
:type step_id: str
:param value:
:type value: list of str
"""
_attribute_map = {
'count': {'key': 'count', 'type': 'int'},
'end_line': {'key': 'endLine', 'type': 'long'},
'start_line': {'key': 'startLine', 'type': 'long'},
'step_id': {'key': 'stepId', 'type': 'str'},
'value': {'key': 'value', 'type': '[str]'}
}
def __init__(self, count=None, end_line=None, start_line=None, step_id=None, value=None):
super(TimelineRecordFeedLinesWrapper, self).__init__()
self.count = count
self.end_line = end_line
self.start_line = start_line
self.step_id = step_id
self.value = value
class TimelineReference(Model):
"""
A reference to a timeline.
:param change_id: The change ID.
:type change_id: int
:param id: The ID of the timeline.
:type id: str
:param location: The REST URL of the timeline.
:type location: str
"""
_attribute_map = {
'change_id': {'key': 'changeId', 'type': 'int'},
'id': {'key': 'id', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'}
}
def __init__(self, change_id=None, id=None, location=None):
super(TimelineReference, self).__init__()
self.change_id = change_id
self.id = id
self.location = location
class VariableValue(Model):
"""
A wrapper class for a generic variable.
:param is_read_only: Indicates whether the variable can be changed during script's execution runtime.
:type is_read_only: bool
:param is_secret: Indicates whether the variable should be encrypted at rest.
:type is_secret: bool
:param value: The value of the variable.
:type value: str
"""
_attribute_map = {
'is_read_only': {'key': 'isReadOnly', 'type': 'bool'},
'is_secret': {'key': 'isSecret', 'type': 'bool'},
'value': {'key': 'value', 'type': 'str'}
}
def __init__(self, is_read_only=None, is_secret=None, value=None):
super(VariableValue, self).__init__()
self.is_read_only = is_read_only
self.is_secret = is_secret
self.value = value
class TaskLog(TaskLogReference):
"""
A task log connected to a timeline record.
:param id: The ID of the task log.
:type id: int
:param location: The REST URL of the task log.
:type location: str
:param created_on: The time of the task log creation.
:type created_on: datetime
:param index_location: The REST URL of the task log when indexed.
:type index_location: str
:param last_changed_on: The time of the last modification of the task log.
:type last_changed_on: datetime
:param line_count: The number of the task log lines.
:type line_count: long
:param path: The path of the task log.
:type path: str
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'int'},
'location': {'key': 'location', 'type': 'str'},
'created_on': {'key': 'createdOn', 'type': 'iso-8601'},
'index_location': {'key': 'indexLocation', 'type': 'str'},
'last_changed_on': {'key': 'lastChangedOn', 'type': 'iso-8601'},
'line_count': {'key': 'lineCount', 'type': 'long'},
'path': {'key': 'path', 'type': 'str'}
}
def __init__(self, id=None, location=None, created_on=None, index_location=None, last_changed_on=None, line_count=None, path=None):
super(TaskLog, self).__init__(id=id, location=location)
self.created_on = created_on
self.index_location = index_location
self.last_changed_on = last_changed_on
self.line_count = line_count
self.path = path
class TaskOrchestrationContainer(TaskOrchestrationItem):
"""
:param item_type:
:type item_type: object
:param continue_on_error:
:type continue_on_error: bool
:param data:
:type data: dict
:param children:
:type children: list of :class:`TaskOrchestrationItem <azure.devops.v7_1.task.models.TaskOrchestrationItem>`
:param max_concurrency:
:type max_concurrency: int
:param parallel:
:type parallel: bool
:param rollback:
:type rollback: :class:`TaskOrchestrationContainer <azure.devops.v7_1.task.models.TaskOrchestrationContainer>`
"""
_attribute_map = {
'item_type': {'key': 'itemType', 'type': 'object'},
'continue_on_error': {'key': 'continueOnError', 'type': 'bool'},
'data': {'key': 'data', 'type': '{str}'},
'children': {'key': 'children', 'type': '[TaskOrchestrationItem]'},
'max_concurrency': {'key': 'maxConcurrency', 'type': 'int'},
'parallel': {'key': 'parallel', 'type': 'bool'},
'rollback': {'key': 'rollback', 'type': 'TaskOrchestrationContainer'}
}
def __init__(self, item_type=None, continue_on_error=None, data=None, children=None, max_concurrency=None, parallel=None, rollback=None):
super(TaskOrchestrationContainer, self).__init__(item_type=item_type)
self.continue_on_error = continue_on_error
self.data = data
self.children = children
self.max_concurrency = max_concurrency
self.parallel = parallel
self.rollback = rollback
class TaskOrchestrationPlan(TaskOrchestrationPlanReference):
"""
:param artifact_location:
:type artifact_location: str
:param artifact_uri:
:type artifact_uri: str
:param definition:
:type definition: :class:`TaskOrchestrationOwner <azure.devops.v7_1.task.models.TaskOrchestrationOwner>`
:param owner:
:type owner: :class:`TaskOrchestrationOwner <azure.devops.v7_1.task.models.TaskOrchestrationOwner>`
:param plan_group:
:type plan_group: str
:param plan_id:
:type plan_id: str
:param plan_type:
:type plan_type: str
:param scope_identifier:
:type scope_identifier: str
:param version:
:type version: int
:param environment:
:type environment: :class:`PlanEnvironment <azure.devops.v7_1.task.models.PlanEnvironment>`
:param expanded_yaml:
:type expanded_yaml: :class:`TaskLogReference <azure.devops.v7_1.task.models.TaskLogReference>`
:param finish_time:
:type finish_time: datetime
:param implementation:
:type implementation: :class:`TaskOrchestrationContainer <azure.devops.v7_1.task.models.TaskOrchestrationContainer>`
:param initialization_log:
:type initialization_log: :class:`TaskLogReference <azure.devops.v7_1.task.models.TaskLogReference>`
:param requested_by_id:
:type requested_by_id: str
:param requested_for_id:
:type requested_for_id: str
:param result:
:type result: object
:param result_code:
:type result_code: str
:param start_time:
:type start_time: datetime
:param state:
:type state: object
:param timeline:
:type timeline: :class:`TimelineReference <azure.devops.v7_1.task.models.TimelineReference>`
"""
_attribute_map = {
'artifact_location': {'key': 'artifactLocation', 'type': 'str'},
'artifact_uri': {'key': 'artifactUri', 'type': 'str'},
'definition': {'key': 'definition', 'type': 'TaskOrchestrationOwner'},
'owner': {'key': 'owner', 'type': 'TaskOrchestrationOwner'},
'plan_group': {'key': 'planGroup', 'type': 'str'},
'plan_id': {'key': 'planId', 'type': 'str'},
'plan_type': {'key': 'planType', 'type': 'str'},
'scope_identifier': {'key': 'scopeIdentifier', 'type': 'str'},
'version': {'key': 'version', 'type': 'int'},
'environment': {'key': 'environment', 'type': 'PlanEnvironment'},
'expanded_yaml': {'key': 'expandedYaml', 'type': 'TaskLogReference'},
'finish_time': {'key': 'finishTime', 'type': 'iso-8601'},
'implementation': {'key': 'implementation', 'type': 'TaskOrchestrationContainer'},
'initialization_log': {'key': 'initializationLog', 'type': 'TaskLogReference'},
'requested_by_id': {'key': 'requestedById', 'type': 'str'},
'requested_for_id': {'key': 'requestedForId', 'type': 'str'},
'result': {'key': 'result', 'type': 'object'},
'result_code': {'key': 'resultCode', 'type': 'str'},
'start_time': {'key': 'startTime', 'type': 'iso-8601'},
'state': {'key': 'state', 'type': 'object'},
'timeline': {'key': 'timeline', 'type': 'TimelineReference'}
}
def __init__(self, artifact_location=None, artifact_uri=None, definition=None, owner=None, plan_group=None, plan_id=None, plan_type=None, scope_identifier=None, version=None, environment=None, expanded_yaml=None, finish_time=None, implementation=None, initialization_log=None, requested_by_id=None, requested_for_id=None, result=None, result_code=None, start_time=None, state=None, timeline=None):
super(TaskOrchestrationPlan, self).__init__(artifact_location=artifact_location, artifact_uri=artifact_uri, definition=definition, owner=owner, plan_group=plan_group, plan_id=plan_id, plan_type=plan_type, scope_identifier=scope_identifier, version=version)
self.environment = environment
self.expanded_yaml = expanded_yaml
self.finish_time = finish_time
self.implementation = implementation
self.initialization_log = initialization_log
self.requested_by_id = requested_by_id
self.requested_for_id = requested_for_id
self.result = result
self.result_code = result_code
self.start_time = start_time
self.state = state
self.timeline = timeline
class Timeline(TimelineReference):
"""
:param change_id: The change ID.
:type change_id: int
:param id: The ID of the timeline.
:type id: str
:param location: The REST URL of the timeline.
:type location: str
:param last_changed_by:
:type last_changed_by: str
:param last_changed_on:
:type last_changed_on: datetime
:param records:
:type records: list of :class:`TimelineRecord <azure.devops.v7_1.task.models.TimelineRecord>`
"""
_attribute_map = {
'change_id': {'key': 'changeId', 'type': 'int'},
'id': {'key': 'id', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'last_changed_by': {'key': 'lastChangedBy', 'type': 'str'},
'last_changed_on': {'key': 'lastChangedOn', 'type': 'iso-8601'},
'records': {'key': 'records', 'type': '[TimelineRecord]'}
}
def __init__(self, change_id=None, id=None, location=None, last_changed_by=None, last_changed_on=None, records=None):
super(Timeline, self).__init__(change_id=change_id, id=id, location=location)
self.last_changed_by = last_changed_by
self.last_changed_on = last_changed_on
self.records = records
__all__ = [
'Issue',
'JobEvent',
'JobOption',
'MaskHint',
'PlanEnvironment',
'ProjectReference',
'ReferenceLinks',
'TaskAgentJob',
'TaskAgentJobStep',
'TaskAgentJobTask',
'TaskAgentJobVariable',
'TaskAttachment',
'TaskHubOidcToken',
'TaskLogReference',
'TaskOrchestrationItem',
'TaskOrchestrationOwner',
'TaskOrchestrationPlanGroupsQueueMetrics',
'TaskOrchestrationPlanReference',
'TaskOrchestrationQueuedPlan',
'TaskOrchestrationQueuedPlanGroup',
'TaskReference',
'TimelineAttempt',
'TimelineRecord',
'TimelineRecordFeedLinesWrapper',
'TimelineReference',
'VariableValue',
'TaskLog',
'TaskOrchestrationContainer',
'TaskOrchestrationPlan',
'Timeline',
]
|
azure-devops-python-api/azure-devops/azure/devops/v7_1/task/models.py/0
|
{
"file_path": "azure-devops-python-api/azure-devops/azure/devops/v7_1/task/models.py",
"repo_id": "azure-devops-python-api",
"token_count": 15613
}
| 367 |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
# Generated file, DO NOT EDIT
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------------------------
from msrest import Serializer, Deserializer
from ...client import Client
from . import models
class TfvcClient(Client):
"""Tfvc
:param str base_url: Service URL
:param Authentication creds: Authenticated credentials.
"""
def __init__(self, base_url=None, creds=None):
super(TfvcClient, self).__init__(base_url, creds)
client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
self._serialize = Serializer(client_models)
self._deserialize = Deserializer(client_models)
resource_area_identifier = '8aa40520-446d-40e6-89f6-9c9f9ce44c48'
def get_branch(self, path, project=None, include_parent=None, include_children=None):
"""GetBranch.
[Preview API] Get a single branch hierarchy at the given path with parents or children as specified.
:param str path: Full path to the branch. Default: $/ Examples: $/, $/MyProject, $/MyProject/SomeFolder.
:param str project: Project ID or project name
:param bool include_parent: Return the parent branch, if there is one. Default: False
:param bool include_children: Return child branches, if there are any. Default: False
:rtype: :class:`<TfvcBranch> <azure.devops.v7_1.tfvc.models.TfvcBranch>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
query_parameters = {}
if path is not None:
query_parameters['path'] = self._serialize.query('path', path, 'str')
if include_parent is not None:
query_parameters['includeParent'] = self._serialize.query('include_parent', include_parent, 'bool')
if include_children is not None:
query_parameters['includeChildren'] = self._serialize.query('include_children', include_children, 'bool')
response = self._send(http_method='GET',
location_id='bc1f417e-239d-42e7-85e1-76e80cb2d6eb',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('TfvcBranch', response)
def get_branches(self, project=None, include_parent=None, include_children=None, include_deleted=None, include_links=None):
"""GetBranches.
[Preview API] Get a collection of branch roots -- first-level children, branches with no parents.
:param str project: Project ID or project name
:param bool include_parent: Return the parent branch, if there is one. Default: False
:param bool include_children: Return the child branches for each root branch. Default: False
:param bool include_deleted: Return deleted branches. Default: False
:param bool include_links: Return links. Default: False
:rtype: [TfvcBranch]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
query_parameters = {}
if include_parent is not None:
query_parameters['includeParent'] = self._serialize.query('include_parent', include_parent, 'bool')
if include_children is not None:
query_parameters['includeChildren'] = self._serialize.query('include_children', include_children, 'bool')
if include_deleted is not None:
query_parameters['includeDeleted'] = self._serialize.query('include_deleted', include_deleted, 'bool')
if include_links is not None:
query_parameters['includeLinks'] = self._serialize.query('include_links', include_links, 'bool')
response = self._send(http_method='GET',
location_id='bc1f417e-239d-42e7-85e1-76e80cb2d6eb',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('[TfvcBranch]', self._unwrap_collection(response))
def get_branch_refs(self, scope_path, project=None, include_deleted=None, include_links=None):
"""GetBranchRefs.
[Preview API] Get branch hierarchies below the specified scopePath
:param str scope_path: Full path to the branch. Default: $/ Examples: $/, $/MyProject, $/MyProject/SomeFolder.
:param str project: Project ID or project name
:param bool include_deleted: Return deleted branches. Default: False
:param bool include_links: Return links. Default: False
:rtype: [TfvcBranchRef]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
query_parameters = {}
if scope_path is not None:
query_parameters['scopePath'] = self._serialize.query('scope_path', scope_path, 'str')
if include_deleted is not None:
query_parameters['includeDeleted'] = self._serialize.query('include_deleted', include_deleted, 'bool')
if include_links is not None:
query_parameters['includeLinks'] = self._serialize.query('include_links', include_links, 'bool')
response = self._send(http_method='GET',
location_id='bc1f417e-239d-42e7-85e1-76e80cb2d6eb',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('[TfvcBranchRef]', self._unwrap_collection(response))
def get_changeset_changes(self, id=None, skip=None, top=None, continuation_token=None):
"""GetChangesetChanges.
[Preview API] Retrieve Tfvc changes for a given changeset.
:param int id: ID of the changeset. Default: null
:param int skip: Number of results to skip. Default: null
:param int top: The maximum number of results to return. Default: null
:param str continuation_token: Return the next page of results. Default: null
:rtype: :class:`<[TfvcChange]> <azure.devops.v7_1.tfvc.models.[TfvcChange]>`
"""
route_values = {}
if id is not None:
route_values['id'] = self._serialize.url('id', id, 'int')
query_parameters = {}
if skip is not None:
query_parameters['$skip'] = self._serialize.query('skip', skip, 'int')
if top is not None:
query_parameters['$top'] = self._serialize.query('top', top, 'int')
if continuation_token is not None:
query_parameters['continuationToken'] = self._serialize.query('continuation_token', continuation_token, 'str')
response = self._send(http_method='GET',
location_id='f32b86f2-15b9-4fe6-81b1-6f8938617ee5',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('[TfvcChange]', self._unwrap_collection(response))
def create_changeset(self, changeset, project=None):
"""CreateChangeset.
[Preview API] Create a new changeset.
:param :class:`<TfvcChangeset> <azure.devops.v7_1.tfvc.models.TfvcChangeset>` changeset:
:param str project: Project ID or project name
:rtype: :class:`<TfvcChangesetRef> <azure.devops.v7_1.tfvc.models.TfvcChangesetRef>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
content = self._serialize.body(changeset, 'TfvcChangeset')
response = self._send(http_method='POST',
location_id='0bc8f0a4-6bfb-42a9-ba84-139da7b99c49',
version='7.1-preview.3',
route_values=route_values,
content=content)
return self._deserialize('TfvcChangesetRef', response)
def get_changeset(self, id, project=None, max_change_count=None, include_details=None, include_work_items=None, max_comment_length=None, include_source_rename=None, skip=None, top=None, orderby=None, search_criteria=None):
"""GetChangeset.
[Preview API] Retrieve a Tfvc Changeset
:param int id: Changeset Id to retrieve.
:param str project: Project ID or project name
:param int max_change_count: Number of changes to return (maximum 100 changes) Default: 0
:param bool include_details: Include policy details and check-in notes in the response. Default: false
:param bool include_work_items: Include workitems. Default: false
:param int max_comment_length: Include details about associated work items in the response. Default: null
:param bool include_source_rename: Include renames. Default: false
:param int skip: Number of results to skip. Default: null
:param int top: The maximum number of results to return. Default: null
:param str orderby: Results are sorted by ID in descending order by default. Use id asc to sort by ID in ascending order.
:param :class:`<TfvcChangesetSearchCriteria> <azure.devops.v7_1.tfvc.models.TfvcChangesetSearchCriteria>` search_criteria: Following criteria available (.itemPath, .version, .versionType, .versionOption, .author, .fromId, .toId, .fromDate, .toDate) Default: null
:rtype: :class:`<TfvcChangeset> <azure.devops.v7_1.tfvc.models.TfvcChangeset>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if id is not None:
route_values['id'] = self._serialize.url('id', id, 'int')
query_parameters = {}
if max_change_count is not None:
query_parameters['maxChangeCount'] = self._serialize.query('max_change_count', max_change_count, 'int')
if include_details is not None:
query_parameters['includeDetails'] = self._serialize.query('include_details', include_details, 'bool')
if include_work_items is not None:
query_parameters['includeWorkItems'] = self._serialize.query('include_work_items', include_work_items, 'bool')
if max_comment_length is not None:
query_parameters['maxCommentLength'] = self._serialize.query('max_comment_length', max_comment_length, 'int')
if include_source_rename is not None:
query_parameters['includeSourceRename'] = self._serialize.query('include_source_rename', include_source_rename, 'bool')
if skip is not None:
query_parameters['$skip'] = self._serialize.query('skip', skip, 'int')
if top is not None:
query_parameters['$top'] = self._serialize.query('top', top, 'int')
if orderby is not None:
query_parameters['$orderby'] = self._serialize.query('orderby', orderby, 'str')
if search_criteria is not None:
if search_criteria.item_path is not None:
query_parameters['searchCriteria.itemPath'] = search_criteria.item_path
if search_criteria.author is not None:
query_parameters['searchCriteria.author'] = search_criteria.author
if search_criteria.from_date is not None:
query_parameters['searchCriteria.fromDate'] = search_criteria.from_date
if search_criteria.to_date is not None:
query_parameters['searchCriteria.toDate'] = search_criteria.to_date
if search_criteria.from_id is not None:
query_parameters['searchCriteria.fromId'] = search_criteria.from_id
if search_criteria.to_id is not None:
query_parameters['searchCriteria.toId'] = search_criteria.to_id
if search_criteria.follow_renames is not None:
query_parameters['searchCriteria.followRenames'] = search_criteria.follow_renames
if search_criteria.include_links is not None:
query_parameters['searchCriteria.includeLinks'] = search_criteria.include_links
if search_criteria.mappings is not None:
query_parameters['searchCriteria.mappings'] = search_criteria.mappings
response = self._send(http_method='GET',
location_id='0bc8f0a4-6bfb-42a9-ba84-139da7b99c49',
version='7.1-preview.3',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('TfvcChangeset', response)
def get_changesets(self, project=None, max_comment_length=None, skip=None, top=None, orderby=None, search_criteria=None):
"""GetChangesets.
[Preview API] Retrieve Tfvc Changesets
:param str project: Project ID or project name
:param int max_comment_length: Include details about associated work items in the response. Default: null
:param int skip: Number of results to skip. Default: null
:param int top: The maximum number of results to return. Default: null
:param str orderby: Results are sorted by ID in descending order by default. Use id asc to sort by ID in ascending order.
:param :class:`<TfvcChangesetSearchCriteria> <azure.devops.v7_1.tfvc.models.TfvcChangesetSearchCriteria>` search_criteria: Following criteria available (.itemPath, .version, .versionType, .versionOption, .author, .fromId, .toId, .fromDate, .toDate) Default: null
:rtype: [TfvcChangesetRef]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
query_parameters = {}
if max_comment_length is not None:
query_parameters['maxCommentLength'] = self._serialize.query('max_comment_length', max_comment_length, 'int')
if skip is not None:
query_parameters['$skip'] = self._serialize.query('skip', skip, 'int')
if top is not None:
query_parameters['$top'] = self._serialize.query('top', top, 'int')
if orderby is not None:
query_parameters['$orderby'] = self._serialize.query('orderby', orderby, 'str')
if search_criteria is not None:
if search_criteria.item_path is not None:
query_parameters['searchCriteria.itemPath'] = search_criteria.item_path
if search_criteria.author is not None:
query_parameters['searchCriteria.author'] = search_criteria.author
if search_criteria.from_date is not None:
query_parameters['searchCriteria.fromDate'] = search_criteria.from_date
if search_criteria.to_date is not None:
query_parameters['searchCriteria.toDate'] = search_criteria.to_date
if search_criteria.from_id is not None:
query_parameters['searchCriteria.fromId'] = search_criteria.from_id
if search_criteria.to_id is not None:
query_parameters['searchCriteria.toId'] = search_criteria.to_id
if search_criteria.follow_renames is not None:
query_parameters['searchCriteria.followRenames'] = search_criteria.follow_renames
if search_criteria.include_links is not None:
query_parameters['searchCriteria.includeLinks'] = search_criteria.include_links
if search_criteria.mappings is not None:
query_parameters['searchCriteria.mappings'] = search_criteria.mappings
response = self._send(http_method='GET',
location_id='0bc8f0a4-6bfb-42a9-ba84-139da7b99c49',
version='7.1-preview.3',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('[TfvcChangesetRef]', self._unwrap_collection(response))
def get_batched_changesets(self, changesets_request_data):
"""GetBatchedChangesets.
[Preview API] Returns changesets for a given list of changeset Ids.
:param :class:`<TfvcChangesetsRequestData> <azure.devops.v7_1.tfvc.models.TfvcChangesetsRequestData>` changesets_request_data: List of changeset IDs.
:rtype: [TfvcChangesetRef]
"""
content = self._serialize.body(changesets_request_data, 'TfvcChangesetsRequestData')
response = self._send(http_method='POST',
location_id='b7e7c173-803c-4fea-9ec8-31ee35c5502a',
version='7.1-preview.1',
content=content)
return self._deserialize('[TfvcChangesetRef]', self._unwrap_collection(response))
def get_changeset_work_items(self, id=None):
"""GetChangesetWorkItems.
[Preview API] Retrieves the work items associated with a particular changeset.
:param int id: ID of the changeset.
:rtype: [AssociatedWorkItem]
"""
route_values = {}
if id is not None:
route_values['id'] = self._serialize.url('id', id, 'int')
response = self._send(http_method='GET',
location_id='64ae0bea-1d71-47c9-a9e5-fe73f5ea0ff4',
version='7.1-preview.1',
route_values=route_values)
return self._deserialize('[AssociatedWorkItem]', self._unwrap_collection(response))
def get_items_batch(self, item_request_data, project=None):
"""GetItemsBatch.
[Preview API] Post for retrieving a set of items given a list of paths or a long path. Allows for specifying the recursionLevel and version descriptors for each path.
:param :class:`<TfvcItemRequestData> <azure.devops.v7_1.tfvc.models.TfvcItemRequestData>` item_request_data:
:param str project: Project ID or project name
:rtype: [[TfvcItem]]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
content = self._serialize.body(item_request_data, 'TfvcItemRequestData')
response = self._send(http_method='POST',
location_id='fe6f827b-5f64-480f-b8af-1eca3b80e833',
version='7.1-preview.1',
route_values=route_values,
content=content)
return self._deserialize('[[TfvcItem]]', self._unwrap_collection(response))
def get_items_batch_zip(self, item_request_data, project=None, **kwargs):
"""GetItemsBatchZip.
[Preview API] Post for retrieving a set of items given a list of paths or a long path. Allows for specifying the recursionLevel and version descriptors for each path.
:param :class:`<TfvcItemRequestData> <azure.devops.v7_1.tfvc.models.TfvcItemRequestData>` item_request_data:
:param str project: Project ID or project name
:rtype: object
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
content = self._serialize.body(item_request_data, 'TfvcItemRequestData')
response = self._send(http_method='POST',
location_id='fe6f827b-5f64-480f-b8af-1eca3b80e833',
version='7.1-preview.1',
route_values=route_values,
content=content,
accept_media_type='application/zip')
if "callback" in kwargs:
callback = kwargs["callback"]
else:
callback = None
return self._client.stream_download(response, callback=callback)
def get_item(self, path, project=None, file_name=None, download=None, scope_path=None, recursion_level=None, version_descriptor=None, include_content=None):
"""GetItem.
[Preview API] Get Item Metadata and/or Content for a single item. The download parameter is to indicate whether the content should be available as a download or just sent as a stream in the response. Doesn't apply to zipped content which is always returned as a download.
:param str path: Version control path of an individual item to return.
:param str project: Project ID or project name
:param str file_name: file name of item returned.
:param bool download: If true, create a downloadable attachment.
:param str scope_path: Version control path of a folder to return multiple items.
:param str recursion_level: None (just the item), or OneLevel (contents of a folder).
:param :class:`<TfvcVersionDescriptor> <azure.devops.v7_1.tfvc.models.TfvcVersionDescriptor>` version_descriptor: Version descriptor. Default is null.
:param bool include_content: Set to true to include item content when requesting json. Default is false.
:rtype: :class:`<TfvcItem> <azure.devops.v7_1.tfvc.models.TfvcItem>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
query_parameters = {}
if path is not None:
query_parameters['path'] = self._serialize.query('path', path, 'str')
if file_name is not None:
query_parameters['fileName'] = self._serialize.query('file_name', file_name, 'str')
if download is not None:
query_parameters['download'] = self._serialize.query('download', download, 'bool')
if scope_path is not None:
query_parameters['scopePath'] = self._serialize.query('scope_path', scope_path, 'str')
if recursion_level is not None:
query_parameters['recursionLevel'] = self._serialize.query('recursion_level', recursion_level, 'str')
if version_descriptor is not None:
if version_descriptor.version_option is not None:
query_parameters['versionDescriptor.versionOption'] = version_descriptor.version_option
if version_descriptor.version_type is not None:
query_parameters['versionDescriptor.versionType'] = version_descriptor.version_type
if version_descriptor.version is not None:
query_parameters['versionDescriptor.version'] = version_descriptor.version
if include_content is not None:
query_parameters['includeContent'] = self._serialize.query('include_content', include_content, 'bool')
response = self._send(http_method='GET',
location_id='ba9fc436-9a38-4578-89d6-e4f3241f5040',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('TfvcItem', response)
def get_item_content(self, path, project=None, file_name=None, download=None, scope_path=None, recursion_level=None, version_descriptor=None, include_content=None, **kwargs):
"""GetItemContent.
[Preview API] Get Item Metadata and/or Content for a single item. The download parameter is to indicate whether the content should be available as a download or just sent as a stream in the response. Doesn't apply to zipped content which is always returned as a download.
:param str path: Version control path of an individual item to return.
:param str project: Project ID or project name
:param str file_name: file name of item returned.
:param bool download: If true, create a downloadable attachment.
:param str scope_path: Version control path of a folder to return multiple items.
:param str recursion_level: None (just the item), or OneLevel (contents of a folder).
:param :class:`<TfvcVersionDescriptor> <azure.devops.v7_1.tfvc.models.TfvcVersionDescriptor>` version_descriptor: Version descriptor. Default is null.
:param bool include_content: Set to true to include item content when requesting json. Default is false.
:rtype: object
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
query_parameters = {}
if path is not None:
query_parameters['path'] = self._serialize.query('path', path, 'str')
if file_name is not None:
query_parameters['fileName'] = self._serialize.query('file_name', file_name, 'str')
if download is not None:
query_parameters['download'] = self._serialize.query('download', download, 'bool')
if scope_path is not None:
query_parameters['scopePath'] = self._serialize.query('scope_path', scope_path, 'str')
if recursion_level is not None:
query_parameters['recursionLevel'] = self._serialize.query('recursion_level', recursion_level, 'str')
if version_descriptor is not None:
if version_descriptor.version_option is not None:
query_parameters['versionDescriptor.versionOption'] = version_descriptor.version_option
if version_descriptor.version_type is not None:
query_parameters['versionDescriptor.versionType'] = version_descriptor.version_type
if version_descriptor.version is not None:
query_parameters['versionDescriptor.version'] = version_descriptor.version
if include_content is not None:
query_parameters['includeContent'] = self._serialize.query('include_content', include_content, 'bool')
response = self._send(http_method='GET',
location_id='ba9fc436-9a38-4578-89d6-e4f3241f5040',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters,
accept_media_type='application/octet-stream')
if "callback" in kwargs:
callback = kwargs["callback"]
else:
callback = None
return self._client.stream_download(response, callback=callback)
def get_items(self, project=None, scope_path=None, recursion_level=None, include_links=None, version_descriptor=None):
"""GetItems.
[Preview API] Get a list of Tfvc items
:param str project: Project ID or project name
:param str scope_path: Version control path of a folder to return multiple items.
:param str recursion_level: None (just the item), or OneLevel (contents of a folder).
:param bool include_links: True to include links.
:param :class:`<TfvcVersionDescriptor> <azure.devops.v7_1.tfvc.models.TfvcVersionDescriptor>` version_descriptor:
:rtype: [TfvcItem]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
query_parameters = {}
if scope_path is not None:
query_parameters['scopePath'] = self._serialize.query('scope_path', scope_path, 'str')
if recursion_level is not None:
query_parameters['recursionLevel'] = self._serialize.query('recursion_level', recursion_level, 'str')
if include_links is not None:
query_parameters['includeLinks'] = self._serialize.query('include_links', include_links, 'bool')
if version_descriptor is not None:
if version_descriptor.version_option is not None:
query_parameters['versionDescriptor.versionOption'] = version_descriptor.version_option
if version_descriptor.version_type is not None:
query_parameters['versionDescriptor.versionType'] = version_descriptor.version_type
if version_descriptor.version is not None:
query_parameters['versionDescriptor.version'] = version_descriptor.version
response = self._send(http_method='GET',
location_id='ba9fc436-9a38-4578-89d6-e4f3241f5040',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('[TfvcItem]', self._unwrap_collection(response))
def get_item_text(self, path, project=None, file_name=None, download=None, scope_path=None, recursion_level=None, version_descriptor=None, include_content=None, **kwargs):
"""GetItemText.
[Preview API] Get Item Metadata and/or Content for a single item. The download parameter is to indicate whether the content should be available as a download or just sent as a stream in the response. Doesn't apply to zipped content which is always returned as a download.
:param str path: Version control path of an individual item to return.
:param str project: Project ID or project name
:param str file_name: file name of item returned.
:param bool download: If true, create a downloadable attachment.
:param str scope_path: Version control path of a folder to return multiple items.
:param str recursion_level: None (just the item), or OneLevel (contents of a folder).
:param :class:`<TfvcVersionDescriptor> <azure.devops.v7_1.tfvc.models.TfvcVersionDescriptor>` version_descriptor: Version descriptor. Default is null.
:param bool include_content: Set to true to include item content when requesting json. Default is false.
:rtype: object
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
query_parameters = {}
if path is not None:
query_parameters['path'] = self._serialize.query('path', path, 'str')
if file_name is not None:
query_parameters['fileName'] = self._serialize.query('file_name', file_name, 'str')
if download is not None:
query_parameters['download'] = self._serialize.query('download', download, 'bool')
if scope_path is not None:
query_parameters['scopePath'] = self._serialize.query('scope_path', scope_path, 'str')
if recursion_level is not None:
query_parameters['recursionLevel'] = self._serialize.query('recursion_level', recursion_level, 'str')
if version_descriptor is not None:
if version_descriptor.version_option is not None:
query_parameters['versionDescriptor.versionOption'] = version_descriptor.version_option
if version_descriptor.version_type is not None:
query_parameters['versionDescriptor.versionType'] = version_descriptor.version_type
if version_descriptor.version is not None:
query_parameters['versionDescriptor.version'] = version_descriptor.version
if include_content is not None:
query_parameters['includeContent'] = self._serialize.query('include_content', include_content, 'bool')
response = self._send(http_method='GET',
location_id='ba9fc436-9a38-4578-89d6-e4f3241f5040',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters,
accept_media_type='text/plain')
if "callback" in kwargs:
callback = kwargs["callback"]
else:
callback = None
return self._client.stream_download(response, callback=callback)
def get_item_zip(self, path, project=None, file_name=None, download=None, scope_path=None, recursion_level=None, version_descriptor=None, include_content=None, **kwargs):
"""GetItemZip.
[Preview API] Get Item Metadata and/or Content for a single item. The download parameter is to indicate whether the content should be available as a download or just sent as a stream in the response. Doesn't apply to zipped content which is always returned as a download.
:param str path: Version control path of an individual item to return.
:param str project: Project ID or project name
:param str file_name: file name of item returned.
:param bool download: If true, create a downloadable attachment.
:param str scope_path: Version control path of a folder to return multiple items.
:param str recursion_level: None (just the item), or OneLevel (contents of a folder).
:param :class:`<TfvcVersionDescriptor> <azure.devops.v7_1.tfvc.models.TfvcVersionDescriptor>` version_descriptor: Version descriptor. Default is null.
:param bool include_content: Set to true to include item content when requesting json. Default is false.
:rtype: object
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
query_parameters = {}
if path is not None:
query_parameters['path'] = self._serialize.query('path', path, 'str')
if file_name is not None:
query_parameters['fileName'] = self._serialize.query('file_name', file_name, 'str')
if download is not None:
query_parameters['download'] = self._serialize.query('download', download, 'bool')
if scope_path is not None:
query_parameters['scopePath'] = self._serialize.query('scope_path', scope_path, 'str')
if recursion_level is not None:
query_parameters['recursionLevel'] = self._serialize.query('recursion_level', recursion_level, 'str')
if version_descriptor is not None:
if version_descriptor.version_option is not None:
query_parameters['versionDescriptor.versionOption'] = version_descriptor.version_option
if version_descriptor.version_type is not None:
query_parameters['versionDescriptor.versionType'] = version_descriptor.version_type
if version_descriptor.version is not None:
query_parameters['versionDescriptor.version'] = version_descriptor.version
if include_content is not None:
query_parameters['includeContent'] = self._serialize.query('include_content', include_content, 'bool')
response = self._send(http_method='GET',
location_id='ba9fc436-9a38-4578-89d6-e4f3241f5040',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters,
accept_media_type='application/zip')
if "callback" in kwargs:
callback = kwargs["callback"]
else:
callback = None
return self._client.stream_download(response, callback=callback)
def get_label_items(self, label_id, top=None, skip=None):
"""GetLabelItems.
[Preview API] Get items under a label.
:param str label_id: Unique identifier of label
:param int top: Max number of items to return
:param int skip: Number of items to skip
:rtype: [TfvcItem]
"""
route_values = {}
if label_id is not None:
route_values['labelId'] = self._serialize.url('label_id', label_id, 'str')
query_parameters = {}
if top is not None:
query_parameters['$top'] = self._serialize.query('top', top, 'int')
if skip is not None:
query_parameters['$skip'] = self._serialize.query('skip', skip, 'int')
response = self._send(http_method='GET',
location_id='06166e34-de17-4b60-8cd1-23182a346fda',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('[TfvcItem]', self._unwrap_collection(response))
def get_label(self, label_id, request_data, project=None):
"""GetLabel.
[Preview API] Get a single deep label.
:param str label_id: Unique identifier of label
:param :class:`<TfvcLabelRequestData> <azure.devops.v7_1.tfvc.models.TfvcLabelRequestData>` request_data: maxItemCount
:param str project: Project ID or project name
:rtype: :class:`<TfvcLabel> <azure.devops.v7_1.tfvc.models.TfvcLabel>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if label_id is not None:
route_values['labelId'] = self._serialize.url('label_id', label_id, 'str')
query_parameters = {}
if request_data is not None:
if request_data.label_scope is not None:
query_parameters['requestData.labelScope'] = request_data.label_scope
if request_data.name is not None:
query_parameters['requestData.name'] = request_data.name
if request_data.owner is not None:
query_parameters['requestData.owner'] = request_data.owner
if request_data.item_label_filter is not None:
query_parameters['requestData.itemLabelFilter'] = request_data.item_label_filter
if request_data.max_item_count is not None:
query_parameters['requestData.maxItemCount'] = request_data.max_item_count
if request_data.include_links is not None:
query_parameters['requestData.includeLinks'] = request_data.include_links
response = self._send(http_method='GET',
location_id='a5d9bd7f-b661-4d0e-b9be-d9c16affae54',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('TfvcLabel', response)
def get_labels(self, request_data, project=None, top=None, skip=None):
"""GetLabels.
[Preview API] Get a collection of shallow label references.
:param :class:`<TfvcLabelRequestData> <azure.devops.v7_1.tfvc.models.TfvcLabelRequestData>` request_data: labelScope, name, owner, and itemLabelFilter
:param str project: Project ID or project name
:param int top: Max number of labels to return, defaults to 100 when undefined
:param int skip: Number of labels to skip
:rtype: [TfvcLabelRef]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
query_parameters = {}
if request_data is not None:
if request_data.label_scope is not None:
query_parameters['requestData.labelScope'] = request_data.label_scope
if request_data.name is not None:
query_parameters['requestData.name'] = request_data.name
if request_data.owner is not None:
query_parameters['requestData.owner'] = request_data.owner
if request_data.item_label_filter is not None:
query_parameters['requestData.itemLabelFilter'] = request_data.item_label_filter
if request_data.max_item_count is not None:
query_parameters['requestData.maxItemCount'] = request_data.max_item_count
if request_data.include_links is not None:
query_parameters['requestData.includeLinks'] = request_data.include_links
if top is not None:
query_parameters['$top'] = self._serialize.query('top', top, 'int')
if skip is not None:
query_parameters['$skip'] = self._serialize.query('skip', skip, 'int')
response = self._send(http_method='GET',
location_id='a5d9bd7f-b661-4d0e-b9be-d9c16affae54',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('[TfvcLabelRef]', self._unwrap_collection(response))
def get_shelveset_changes(self, shelveset_id, top=None, skip=None):
"""GetShelvesetChanges.
[Preview API] Get changes included in a shelveset.
:param str shelveset_id: Shelveset's unique ID
:param int top: Max number of changes to return
:param int skip: Number of changes to skip
:rtype: [TfvcChange]
"""
query_parameters = {}
if shelveset_id is not None:
query_parameters['shelvesetId'] = self._serialize.query('shelveset_id', shelveset_id, 'str')
if top is not None:
query_parameters['$top'] = self._serialize.query('top', top, 'int')
if skip is not None:
query_parameters['$skip'] = self._serialize.query('skip', skip, 'int')
response = self._send(http_method='GET',
location_id='dbaf075b-0445-4c34-9e5b-82292f856522',
version='7.1-preview.1',
query_parameters=query_parameters)
return self._deserialize('[TfvcChange]', self._unwrap_collection(response))
def get_shelveset(self, shelveset_id, request_data=None):
"""GetShelveset.
[Preview API] Get a single deep shelveset.
:param str shelveset_id: Shelveset's unique ID
:param :class:`<TfvcShelvesetRequestData> <azure.devops.v7_1.tfvc.models.TfvcShelvesetRequestData>` request_data: includeDetails, includeWorkItems, maxChangeCount, and maxCommentLength
:rtype: :class:`<TfvcShelveset> <azure.devops.v7_1.tfvc.models.TfvcShelveset>`
"""
query_parameters = {}
if shelveset_id is not None:
query_parameters['shelvesetId'] = self._serialize.query('shelveset_id', shelveset_id, 'str')
if request_data is not None:
if request_data.name is not None:
query_parameters['requestData.name'] = request_data.name
if request_data.owner is not None:
query_parameters['requestData.owner'] = request_data.owner
if request_data.max_comment_length is not None:
query_parameters['requestData.maxCommentLength'] = request_data.max_comment_length
if request_data.max_change_count is not None:
query_parameters['requestData.maxChangeCount'] = request_data.max_change_count
if request_data.include_details is not None:
query_parameters['requestData.includeDetails'] = request_data.include_details
if request_data.include_work_items is not None:
query_parameters['requestData.includeWorkItems'] = request_data.include_work_items
if request_data.include_links is not None:
query_parameters['requestData.includeLinks'] = request_data.include_links
response = self._send(http_method='GET',
location_id='e36d44fb-e907-4b0a-b194-f83f1ed32ad3',
version='7.1-preview.1',
query_parameters=query_parameters)
return self._deserialize('TfvcShelveset', response)
def get_shelvesets(self, request_data=None, top=None, skip=None):
"""GetShelvesets.
[Preview API] Return a collection of shallow shelveset references.
:param :class:`<TfvcShelvesetRequestData> <azure.devops.v7_1.tfvc.models.TfvcShelvesetRequestData>` request_data: name, owner, and maxCommentLength
:param int top: Max number of shelvesets to return
:param int skip: Number of shelvesets to skip
:rtype: [TfvcShelvesetRef]
"""
query_parameters = {}
if request_data is not None:
if request_data.name is not None:
query_parameters['requestData.name'] = request_data.name
if request_data.owner is not None:
query_parameters['requestData.owner'] = request_data.owner
if request_data.max_comment_length is not None:
query_parameters['requestData.maxCommentLength'] = request_data.max_comment_length
if request_data.max_change_count is not None:
query_parameters['requestData.maxChangeCount'] = request_data.max_change_count
if request_data.include_details is not None:
query_parameters['requestData.includeDetails'] = request_data.include_details
if request_data.include_work_items is not None:
query_parameters['requestData.includeWorkItems'] = request_data.include_work_items
if request_data.include_links is not None:
query_parameters['requestData.includeLinks'] = request_data.include_links
if top is not None:
query_parameters['$top'] = self._serialize.query('top', top, 'int')
if skip is not None:
query_parameters['$skip'] = self._serialize.query('skip', skip, 'int')
response = self._send(http_method='GET',
location_id='e36d44fb-e907-4b0a-b194-f83f1ed32ad3',
version='7.1-preview.1',
query_parameters=query_parameters)
return self._deserialize('[TfvcShelvesetRef]', self._unwrap_collection(response))
def get_shelveset_work_items(self, shelveset_id):
"""GetShelvesetWorkItems.
[Preview API] Get work items associated with a shelveset.
:param str shelveset_id: Shelveset's unique ID
:rtype: [AssociatedWorkItem]
"""
query_parameters = {}
if shelveset_id is not None:
query_parameters['shelvesetId'] = self._serialize.query('shelveset_id', shelveset_id, 'str')
response = self._send(http_method='GET',
location_id='a7a0c1c1-373e-425a-b031-a519474d743d',
version='7.1-preview.1',
query_parameters=query_parameters)
return self._deserialize('[AssociatedWorkItem]', self._unwrap_collection(response))
|
azure-devops-python-api/azure-devops/azure/devops/v7_1/tfvc/tfvc_client.py/0
|
{
"file_path": "azure-devops-python-api/azure-devops/azure/devops/v7_1/tfvc/tfvc_client.py",
"repo_id": "azure-devops-python-api",
"token_count": 20075
}
| 368 |
@REM -------------------------------------------------
@REM init section. Set _echo=1 to echo everything....
@IF NOT DEFINED _echo ECHO OFF
IF EXIST "%BUILD_BINARIESDIRECTORY%\python.3.6.2\tools\python.exe" (
REM Build step installs Python here.
SET PYTHONEXE=%BUILD_BINARIESDIRECTORY%\python.3.6.2\tools\python.exe
) ELSE (
SET PYTHONEXE=python.exe
)
"%PYTHONEXE%" %~dp0\..\dev_setup.py
IF ERRORLEVEL 1 GOTO FAIL
SET PYTHONEXE=
GOTO :EOF
:FAIL
ECHO dev_setup failed.
EXIT /B 1
|
azure-devops-python-api/scripts/windows/dev_setup.cmd/0
|
{
"file_path": "azure-devops-python-api/scripts/windows/dev_setup.cmd",
"repo_id": "azure-devops-python-api",
"token_count": 206
}
| 369 |
# Support
## How to file issues and get help
This project uses GitHub Issues to track bugs and feature requests. Please search the existing
issues before filing new issues to avoid duplicates. For new issues, file your bug or
feature request as a new Issue.
## Microsoft Support Policy
Support for this **PROJECT or PRODUCT** is limited to the resources listed above.
|
azure-quantum-python/SUPPORT.md/0
|
{
"file_path": "azure-quantum-python/SUPPORT.md",
"repo_id": "azure-quantum-python",
"token_count": 90
}
| 370 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from ._models import BlobDetails
from ._models import CostEstimate
from ._models import ErrorData
from ._models import ItemDetails
from ._models import JobDetails
from ._models import JsonPatchDocument
from ._models import ProviderStatus
from ._models import QuantumComputingData
from ._models import Quota
from ._models import RestError
from ._models import SasUriResponse
from ._models import SessionDetails
from ._models import TargetStatus
from ._models import UsageEvent
from ._enums import DimensionScope
from ._enums import ItemType
from ._enums import JobStatus
from ._enums import JobType
from ._enums import JsonPatchOperation
from ._enums import MeterPeriod
from ._enums import ProviderAvailability
from ._enums import SessionJobFailurePolicy
from ._enums import SessionStatus
from ._enums import TargetAvailability
from ._patch import __all__ as _patch_all
from ._patch import * # pylint: disable=unused-wildcard-import
from ._patch import patch_sdk as _patch_sdk
__all__ = [
"BlobDetails",
"CostEstimate",
"ErrorData",
"ItemDetails",
"JobDetails",
"JsonPatchDocument",
"ProviderStatus",
"QuantumComputingData",
"Quota",
"RestError",
"SasUriResponse",
"SessionDetails",
"TargetStatus",
"UsageEvent",
"DimensionScope",
"ItemType",
"JobStatus",
"JobType",
"JsonPatchOperation",
"MeterPeriod",
"ProviderAvailability",
"SessionJobFailurePolicy",
"SessionStatus",
"TargetAvailability",
]
__all__.extend([p for p in _patch_all if p not in __all__])
_patch_sdk()
|
azure-quantum-python/azure-quantum/azure/quantum/_client/models/__init__.py/0
|
{
"file_path": "azure-quantum-python/azure-quantum/azure/quantum/_client/models/__init__.py",
"repo_id": "azure-quantum-python",
"token_count": 571
}
| 371 |
##
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
##
"""Defines set of Cirq targets for interacting with Azure Quantum"""
from azure.quantum.cirq.targets.target import Target
from azure.quantum.cirq.targets.quantinuum import QuantinuumTarget
from azure.quantum.cirq.targets.ionq import IonQTarget
__all__ = ["Target", "QuantinuumTarget", "IonQTarget"]
# Default targets to use when there is no target class
# associated with a given target ID
DEFAULT_TARGETS = {
"ionq": IonQTarget,
"quantinuum": QuantinuumTarget,
}
|
azure-quantum-python/azure-quantum/azure/quantum/cirq/targets/__init__.py/0
|
{
"file_path": "azure-quantum-python/azure-quantum/azure/quantum/cirq/targets/__init__.py",
"repo_id": "azure-quantum-python",
"token_count": 182
}
| 372 |
##
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
##
from typing import TYPE_CHECKING, Any, Dict, List
from azure.quantum.version import __version__
from qiskit import QuantumCircuit
from abc import abstractmethod
from .backend import AzureQirBackend
from qiskit.providers.models import BackendConfiguration
from qiskit.providers import Options, Provider
QIR_BASIS_GATES = [
"measure",
"m",
"ccx",
"cx",
"cz",
"h",
"reset",
"rx",
"ry",
"rz",
"s",
"sdg",
"swap",
"t",
"tdg",
"x",
"y",
"z",
"id",
]
if TYPE_CHECKING:
from azure.quantum.qiskit import AzureQuantumProvider
import logging
logger = logging.getLogger(__name__)
__all__ = ["MicrosoftBackend", "MicrosoftResourceEstimationBackend"]
class MicrosoftBackend(AzureQirBackend):
"""Base class for interfacing with a Microsoft backend in Azure Quantum"""
@abstractmethod
def __init__(
self, configuration: BackendConfiguration, provider: Provider = None, **fields
):
super().__init__(configuration, provider, **fields)
@classmethod
def _default_options(cls):
return Options(targetCapability="AdaptiveExecution")
def _azure_config(self) -> Dict[str, str]:
config = super()._azure_config()
config.update(
{
"provider_id": "microsoft-qc",
"output_data_format": "microsoft.resource-estimates.v1",
"to_qir_kwargs": {"record_output": False},
}
)
return config
class MicrosoftResourceEstimationBackend(MicrosoftBackend):
"""Backend class for interfacing with the resource estimator target"""
backend_names = ("microsoft.estimator",)
@classmethod
def _default_options(cls):
return Options(
targetCapability="AdaptiveExecution",
errorBudget=1e-3,
qubitParams={"name": "qubit_gate_ns_e3"},
qecScheme={"name": "surface_code"}
)
def __init__(self, name: str, provider: "AzureQuantumProvider", **kwargs):
"""Constructor for class to interface with the resource estimator target"""
default_config = BackendConfiguration.from_dict(
{
"backend_name": name,
"backend_version": __version__,
"simulator": True,
"local": False,
"coupling_map": None,
"description": "Resource estimator on Azure Quantum",
"basis_gates": QIR_BASIS_GATES,
"memory": False,
"n_qubits": 0xFFFFFFFFFFFFFFFF, # NOTE: maximum 64-bit unsigned value
"conditional": True,
"max_shots": 1,
"max_experiments": 1,
"open_pulse": False,
"gates": [
{"name": "TODO", "parameters": [], "qasm_def": "TODO"}
], # NOTE: copied from other backends
"azure": self._azure_config(),
"is_default": True,
}
)
logger.info("Initializing MicrosoftResourceEstimationBackend")
configuration: BackendConfiguration = kwargs.pop(
"configuration", default_config
)
super().__init__(configuration=configuration, provider=provider, **kwargs)
|
azure-quantum-python/azure-quantum/azure/quantum/qiskit/backends/microsoft.py/0
|
{
"file_path": "azure-quantum-python/azure-quantum/azure/quantum/qiskit/backends/microsoft.py",
"repo_id": "azure-quantum-python",
"token_count": 1516
}
| 373 |
##
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
##
from ... import Job
from ...job.base_job import DEFAULT_TIMEOUT
from ..._client.models import JobDetails
from .result import MicrosoftEstimatorResult
class MicrosoftEstimatorJob(Job):
"""
A dedicated job class for jobs from the microsoft.estimator target.
"""
def __init__(self, workspace, job_details: JobDetails, **kwargs):
super().__init__(workspace, job_details, **kwargs)
def get_results(self, timeout_secs: float = DEFAULT_TIMEOUT) -> MicrosoftEstimatorResult:
"""
Get estimation result.
:param timeout_secs: Timeout in seconds, defaults to 300 sec.
:type timeout_secs: float
:return: Estimation result
:rtype: MicrosoftEstimatorResult
"""
try:
results = super().get_results(timeout_secs)
return MicrosoftEstimatorResult(results)
except RuntimeError:
error_obj = self.details.error_data
message = "Cannot retrieve results as job execution failed " \
f"({error_obj.code}: {error_obj.message})"
raise RuntimeError(message)
|
azure-quantum-python/azure-quantum/azure/quantum/target/microsoft/job.py/0
|
{
"file_path": "azure-quantum-python/azure-quantum/azure/quantum/target/microsoft/job.py",
"repo_id": "azure-quantum-python",
"token_count": 460
}
| 374 |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
[CmdletBinding()]
Param (
[string] $TestFilter = ""
)
$FileFilter = "*${TestFilter}*.yaml"
# Delete old recordings
$Recordings_Folder = Join-Path $PSScriptRoot "../tests/unit/recordings/"
if (Test-Path $Recordings_Folder) {
Get-ChildItem $Recordings_Folder -Recurse -Filter $FileFilter | Remove-Item -Force | Write-Verbose
}
try
{
Push-Location (Join-Path $PSScriptRoot "../tests/")
conda activate azurequantum
if ([string]::IsNullOrEmpty($TestFilter)) {
pytest
}
else {
pytest -k $TestFilter
}
}
finally
{
Pop-Location
}
|
azure-quantum-python/azure-quantum/eng/Record-Tests.ps1/0
|
{
"file_path": "azure-quantum-python/azure-quantum/eng/Record-Tests.ps1",
"repo_id": "azure-quantum-python",
"token_count": 275
}
| 375 |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
<#
.SYNOPSIS
Includes utility cmdlets for working with conda both locally,
and in Azure Pipelines and other hosted environments.
#>
function Test-CondaEnabled {
<#
.SYNOPSIS
Tests if conda has been enabled for shell
use (e.g.: if conda activate will work).
#>
# The shell hook for conda creates a new cmdlet called
# Invoke-Conda that is then aliased to `conda`. If the
# full name (without an alias) is available, then the hook
# has been run already.
if ($null -ne (Get-Command Invoke-Conda -ErrorAction SilentlyContinue)) {
return $true;
}
return $false;
}
function Enable-Conda {
<#
.SYNOPSIS
Attempts to enable conda for shell usage, first using
the CONDA environment variable for the path, falling back
to PATH, and then failing.
If conda is already enabled, this cmdlet does nothing,
so that this cmdlet is idempotent.
#>
if (Test-CondaEnabled) { return $true; }
if ("$Env:CONDA" -ne "") {
# Try and run the shell hook from the path nominated
# by CONDA.
# On Windows, this is $Env:CONDA/Scripts/conda.exe, while on
# Linux and macOS, this is $Env:CONDA/bin/conda.
if ($IsWindows) {
$condaBin = Join-Path $Env:CONDA "Scripts" "conda.exe";
} else {
$condaBin = Join-Path $Env:CONDA "bin" "conda";
}
if ($null -eq (Get-Command $condaBin -ErrorAction SilentlyContinue)) {
Write-Error "##[error] conda binary was expected at $condaBin (CONDA = $Env:CONDA), but was not found.";
throw;
}
(& $condaBin shell.powershell hook) | Out-String | Invoke-Expression;
} else {
(conda shell.powershell hook) | Out-String | Invoke-Expression;
}
}
function Use-CondaEnv {
param (
[string] $EnvName
)
<#
.SYNOPSIS
Activates a conda environment, reporting the new configuration
after having done so. If conda has not already been enabled, this
cmdlet will enable it before activating.
#>
Enable-Conda
# NB: We use the PowerShell cmdlet created by the conda shell hook here
# to avoid accidentally using the conda binary.
Enter-CondaEnvironment $EnvName
Write-Host "##[info]Activated Conda env: $(Get-PythonConfiguration | Out-String)"
}
function Install-Package() {
param(
[string] $EnvName,
[string] $PackageName,
[bool] $FromSource
)
# Activate env
Use-CondaEnv $EnvName
# Install package
if ($True -eq $FromSource) {
$ParentPath = Split-Path -parent $PSScriptRoot
$AbsPackageDir = Join-Path $ParentPath $PackageName
Write-Host "##[info]Install package $AbsPackageDir in development mode for env $EnvName"
pip install -e $AbsPackageDir
} else {
Write-Host "##[info]Install package $PackageName for env $EnvName"
pip install $PackageName
}
}
function Get-PythonConfiguration {
<#
.SYNOPSIS
Returns a table describing the current Python configuration,
useful for diagnostic purposes.
#>
$table = @{};
$python = (Get-Command python -ErrorAction SilentlyContinue);
if ($null -ne $python) {
$table["PythonLocation"] = $python.Source;
try {
$table["PythonVersion"] = & $python --version;
} catch { }
}
# If the CONDA environment variable is set, allow that to override
# the local PATH.
$conda = Get-Command conda -ErrorAction SilentlyContinue;
if ($null -ne $conda) {
$table["CondaLocation"] = $conda.Source;
try {
$table["CondaVersion"] = & $conda --version;
} catch { }
}
# If the conda hook has already been run, we can get some additional
# information for the table.
if (Test-CondaEnabled) {
try {
$env = Get-CondaEnvironment | Where-Object -Property Active;
if ($null -ne $env) {
$table["CondaEnvName"] = $env.Name;
$table["CondaEnvPath"] = $env.Path;
}
} catch { }
}
$table | Write-Output;
}
|
azure-quantum-python/build/conda-utils.psm1/0
|
{
"file_path": "azure-quantum-python/build/conda-utils.psm1",
"repo_id": "azure-quantum-python",
"token_count": 1806
}
| 376 |
<jupyter_start><jupyter_text>Resource Estimation for Double-factorized ChemistryIn this notebook we evaluate the physical resource estimates of using theso-called _double-factorized qubitization_ algorithm described in [[Phys. Rev.Research 3, 033055 (2021)](https://doi.org/10.1103/PhysRevResearch.3.033055)] tocalculate the energy of a user provided Hamiltonian to chemical accuracy of 1mHa. The Hamiltonian is provided in terms of an FCIDUMP file that is accessiblevia an HTTPS URI.The _qubitization_ approach is based on quantum phase estimation, but instead ofconstructing the standard $U = \exp{(-i H/\alpha)}$ from the Hamiltonian matrix$H$, one takes $U = \exp{(-i \sin^{-1} (H/\alpha))}$, which can typically beimplemented with fewer resources. Using _double-factorization_, $H$ isrepresented compactly through a combination of a judicious choice of orbitalsand compression. The tolerated total error budget is $\epsilon = 0.01$,corresponding to $1\%$. Getting startedWe import several Python classes and functions from `azure.quantum`.<jupyter_code>from azure.quantum import Workspace
from azure.quantum.target.microsoft import MicrosoftEstimator
from azure.quantum.chemistry import df_chemistry<jupyter_output><empty_output><jupyter_text>We connect to the Azure Quantum workspace by creating a new workspace.<jupyter_code>workspace = Workspace(
resource_id="",
location=""
)<jupyter_output><empty_output><jupyter_text>This workspace is then used to create an instance to the Resource Estimator.<jupyter_code>estimator = MicrosoftEstimator(workspace)<jupyter_output><empty_output><jupyter_text>Configuring a resource estimation jobWe start by creating a parameter instance for the resource estimator, which allows us to configure all parameters associated to the estimation job. In this scenario, we want to evaluate estimates for six different qubit parameter configurations, therefore we set the number of items in the job to 6.<jupyter_code>params = estimator.make_params(num_items=6)<jupyter_output><empty_output><jupyter_text>Next we are providing a link to the FCIDUMP file that describes the Hamiltonian, which is passed via a URI. For example, you can choose some of the following URIs:| URI | Instance name | Description ||----------------------------------------------|-----------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|| https://aka.ms/fcidump/XVIII-cas4-fb-64e-56o | XVIII-cas4-fb-64e-56o | 64 electron, 56 orbital active space of one of the stable intermediates in the [ruthenium-catalyzed carbon fixation cycle](https://journals.aps.org/prresearch/abstract/10.1103/PhysRevResearch.3.033055) || https://aka.ms/fcidump/nitrogenase-54e-54o | nitrogenase-54e-54o | 54 electron, 54 orbital active space of the active core of the nitrogenase that is used in [this paper](https://www.pnas.org/doi/10.1073/pnas.1619152114) || https://aka.ms/fcidump/fe2s2-10e-40o | fe2s2-10e-40o | 10 electron, 40 orbital active space of [2Fe, 2S] cluster that is shown in [this paper](https://www.nature.com/articles/nchem.2041) || https://aka.ms/fcidump/polyyne-24e-24o | polyyne-24e-24o | 24 electron, 24 orbital active space of the polyyne molecule || https://aka.ms/fcidump/n2-10e-8o | n2-10e-8o | 10 electron, 8 orbital active space of he dissociated nitrogen at 3 Angstrom distance |You can also pass your own FCIDUMP files via * [raw links to files in Github](https://learn.github.com/repositories/working-with-files/using-files/viewing-a-fileviewing-or-copying-the-raw-file-content) repositories (see how to [add files to Github repositories](https://learn.github.com/repositories/working-with-files/managing-files/creating-new-files))* [files on Github gists](https://learn.github.com/get-started/writing-on-github/editing-and-sharing-content-with-gists/creating-gists)* [files in Azure Blob Storage](https://learn.microsoft.com/azure/storage/blobs/storage-blobs-introduction) using [SAS tokens](https://learn.microsoft.com/azure/cognitive-services/translator/document-translation/how-to-guides/create-sas-tokens?tabs=Containerscreate-sas-tokens-in-the-azure-portal)The URI is passed to the parameters as so called file URI with the name `"fcidumpUri"`:<jupyter_code>params.file_uris["fcidumpUri"] = "https://aka.ms/fcidump/XVIII-cas4-fb-64e-56o"<jupyter_output><empty_output><jupyter_text>The quantum algorithms requires a total accuracy if 0.01, i.e., 1%, in order to obtain a chemical accuracy of 1 mHa. We can instruct the resource estimator to use a total error budget of 0.01, which is distributed to all possible sub components in the execution of the quantum algorithm that may fail. (More details on the error budget can be found in the [Azure Quantum documentation](https://learn.microsoft.com/azure/quantum/overview-resources-estimatorerror-budget).)<jupyter_code>params.error_budget = 0.01<jupyter_output><empty_output><jupyter_text>Finally, we are specifying the qubit parameters. Here we are choosing all six pre-defined qubit parameter models. These are four gate-based models with operation times in the microsecond and nanosecond regime, as well as assumptions on their physical error rates of $10^{-3}$ and $10^{-4}$, respectively. The other two are Majorana based models with operation times in the nanosecond regime and physical error rates of $10^{-4}$ and $10^{-6}$. For the Majorana based models we assume a Floquet code as QEC scheme. More details on these parameters and assumptions, as well as how to customize these, can be found in the [Azure Quantum documentation](https://learn.microsoft.com/azure/quantum/overview-resources-estimator).<jupyter_code>params.items[0].qubit_params.name = "qubit_gate_us_e3"
params.items[1].qubit_params.name = "qubit_gate_us_e4"
params.items[2].qubit_params.name = "qubit_gate_ns_e3"
params.items[3].qubit_params.name = "qubit_gate_ns_e4"
params.items[4].qubit_params.name = "qubit_maj_ns_e4"
params.items[4].qec_scheme.name = "floquet_code"
params.items[5].qubit_params.name = "qubit_maj_ns_e6"
params.items[5].qec_scheme.name = "floquet_code"<jupyter_output><empty_output><jupyter_text>The parameters are now all set up, and we are ready to go to submit the resource estimation job. As quantum program, we are using the double-factorization based quantum chemistry algorithm, which is provided via the `df_chemistry` function. The execution of this cell may take a few minutes depending on program size. Once the job is finished, we are obtaining the results.<jupyter_code>job = estimator.submit(df_chemistry(), input_params=params)
results = job.get_results()<jupyter_output><empty_output><jupyter_text>Analyzing the resultsFinally, we are presenting the experimental results using a summary table.<jupyter_code>labels = ["Gate-based µs, 10⁻³", "Gate-based µs, 10⁻⁴", "Gate-based ns, 10⁻³", "Gate-based ns, 10⁻⁴", "Majorana ns, 10⁻⁴", "Majorana ns, 10⁻⁶"]
results.summary_data_frame(labels=labels)<jupyter_output><empty_output><jupyter_text>Each row corresponds to one of the six qubit parameter configurations, where the first column shows a textual description for the model. The next three columns show technology-independent resources, which are the number of logical qubits, the logical depth, which is the number of logical operations performed in sequence, as well as the number of T states that are consumed by the logical operations. T states originate from complex operations in the quantum algorithm, e.g., Toffoli gates or rotation gates.Next, the code distance indicates the error correction overhead to guarantee a sufficient logical error rate for the logical operations. The number of T factories indicates how many T factories are executed in parallel to produce the total number of T states. The T factory fraction describes the percentage of the number of qubits that are used to execute T factories, the rest is used to execute the logical operations of the algorithm. Finally, the last two columns show the total number of physical qubits and the wall clock runtime to execute the quantum algorithm given the assumed qubit parameters. Detailed resource estimatesWe can also have a more detailed look into the resource estimates. Here we show the details for the last configuration (index 5). The output is a table with the overall physical resource counts. You can further inspect more details about the resource estimates by collapsing various groups which have more information. For example, if you collapse the Logical qubit parameters group, you can see how the overhead to represent a logical qubit using physical qubits is derived. The last group shows the physical qubit properties that were assumed for this estimation.<jupyter_code>results[5]<jupyter_output><empty_output><jupyter_text>We can also compare different configurations. In this case we compare the gate-based nanosecond model with the Majorana based model for an error rate of $10^{-4}$. These correspond to indices 3 and 4, not that intervals in Python are half-open.<jupyter_code>results[3:5]<jupyter_output><empty_output>
|
azure-quantum-python/samples/resource-estimator/estimation-chemistry.ipynb/0
|
{
"file_path": "azure-quantum-python/samples/resource-estimator/estimation-chemistry.ipynb",
"repo_id": "azure-quantum-python",
"token_count": 3233
}
| 377 |
module.exports = function (api) {
api.cache(true);
const presets = [ "@babel/preset-env", "@babel/preset-react" ];
const generatorOpts ={"compact" : true};
return {
presets,
generatorOpts
};
}
|
azure-quantum-python/visualization/js-lib/babel.config.js/0
|
{
"file_path": "azure-quantum-python/visualization/js-lib/babel.config.js",
"repo_id": "azure-quantum-python",
"token_count": 99
}
| 378 |
export { SpaceDiagram } from "./resource-estimator";
export { TimeDiagram } from "./resource-estimator";
|
azure-quantum-python/visualization/react-lib/src/components/index.ts/0
|
{
"file_path": "azure-quantum-python/visualization/react-lib/src/components/index.ts",
"repo_id": "azure-quantum-python",
"token_count": 32
}
| 379 |
const path = require('path')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
module.exports = {
entry: './src/index.ts',
output: {
path: path.resolve(__dirname, 'dist'),
libraryTarget: 'commonjs'
},
plugins: [new CleanWebpackPlugin()],
module: {
rules: [
{
test: /\.(ts|tsx)$/,
exclude: /node_modules/,
resolve: {
extensions: ['.ts', '.tsx', '.js', '.jsx', '.json']
},
use: 'ts-loader'
},
{
test: /\.css$/,
use: [
'style-loader',
{ loader: 'css-loader', options: { sourceMap: true } }
],
exclude: /node_modules/
}
]
},
externals: {
react: 'react'
}
}
|
azure-quantum-python/visualization/react-lib/webpack.config.js/0
|
{
"file_path": "azure-quantum-python/visualization/react-lib/webpack.config.js",
"repo_id": "azure-quantum-python",
"token_count": 356
}
| 380 |
bistring
========
|Build status| |Documentation status|
The bistring library provides non-destructive versions of common string processing operations like normalization, case folding, and find/replace.
Each bistring remembers the original string, and how its substrings map to substrings of the modified version.
For example:
.. code-block:: python
>>> from bistring import bistr
>>> s = bistr('𝕿𝖍𝖊 𝖖𝖚𝖎𝖈𝖐, 𝖇𝖗𝖔𝖜𝖓 🦊 𝖏𝖚𝖒𝖕𝖘 𝖔𝖛𝖊𝖗 𝖙𝖍𝖊 𝖑𝖆𝖟𝖞 🐶')
>>> s = s.normalize('NFKD') # Unicode normalization
>>> s = s.casefold() # Case-insensitivity
>>> s = s.replace('🦊', 'fox') # Replace emoji with text
>>> s = s.replace('🐶', 'dog')
>>> s = s.sub(r'[^\w\s]+', '') # Strip everything but letters and spaces
>>> s = s[:19] # Extract a substring
>>> s.modified # The modified substring, after changes
'the quick brown fox'
>>> s.original # The original substring, before changes
'𝕿𝖍𝖊 𝖖𝖚𝖎𝖈𝖐, 𝖇𝖗𝖔𝖜𝖓 🦊'
Languages
---------
|PyPI version| |npm version|
bistring is available in multiple languages, currently `Python <python>`_ and `JavaScript/TypeScript <js>`_.
Ports to other languages are planned for the near future.
The code is structured similarly in each language to make it easy to share algorithms, tests, and fixes between them.
The main differences come from trying to mirror the language's built-in string API.
If you want to contribute a bug fix or a new feature, feel free to implement it in any one of the supported languages, and we'll try to port it to the rest of them.
Demo
----
`Click here <https://microsoft.github.io/bistring/demo.html>`_ for a live demo of the bistring library in your browser.
Contributing
------------
This project welcomes contributions and suggestions.
Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution.
For details, visit https://cla.microsoft.com.
When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment).
Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.
This project has adopted the `Microsoft Open Source Code of Conduct <https://opensource.microsoft.com/codeofconduct/>`_.
For more information see the `Code of Conduct FAQ <https://opensource.microsoft.com/codeofconduct/faq/>`_ or contact `[email protected] <mailto:[email protected]>`_ with any additional questions or comments.
.. |Build status| image:: https://github.com/microsoft/bistring/actions/workflows/ci.yml/badge.svg
:target: https://github.com/microsoft/bistring/actions/workflows/ci.yml
.. |Documentation status| image:: https://readthedocs.org/projects/bistring/badge/?version=latest
:target: https://bistring.readthedocs.io/en/latest/?badge=latest
.. |PyPI version| image:: https://badge.fury.io/py/bistring.svg
:target: https://pypi.org/project/bistring/
.. |npm version| image:: https://badge.fury.io/js/bistring.svg
:target: https://www.npmjs.com/package/bistring
|
bistring/README.rst/0
|
{
"file_path": "bistring/README.rst",
"repo_id": "bistring",
"token_count": 1122
}
| 381 |
Tokenization
============
.. testsetup:: *
from bistring import Tokenization
.. autoclass:: bistring.Token
.. autoclass:: bistring.Tokenization
|
bistring/docs/Python/Tokenization.rst/0
|
{
"file_path": "bistring/docs/Python/Tokenization.rst",
"repo_id": "bistring",
"token_count": 48
}
| 382 |
#!/usr/bin/env python3
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT license.
import icu
from typing import IO
def escape(cp: int) -> str:
if cp < 0x10000:
return f"\\u{cp:04x}"
else:
return f"\\u{{{cp:x}}}"
def gen_boundary_regex(normalizer: icu.Normalizer2) -> str:
ranges = []
for cp in range(0x110000):
if not normalizer.hasBoundaryBefore(chr(cp)):
if ranges and cp == ranges[-1].stop:
ranges[-1] = range(ranges[-1].start, cp + 1)
else:
ranges.append(range(cp, cp + 1))
chunks = ['/.[']
for r in ranges:
chunks.append(escape(r.start))
if len(r) > 1:
chunks.append('-')
chunks.append(escape(r.stop - 1))
chunks.append(']*/gsu')
return "".join(chunks)
def export_boundary_regex(f: IO[str], form: str) -> None:
f.write(f'/**\n')
f.write(f' * Matches until the next {form} normalization boundary.\n')
f.write(f' */\n')
f.write(f'export const {form}_CHUNK = ')
normalizer = getattr(icu.Normalizer2, "get" + form + "Instance")()
f.write(gen_boundary_regex(normalizer))
f.write(';\n')
if __name__ == "__main__":
with open('src/unicode.ts', 'w') as f:
f.write('/**\n')
f.write(' * GENERATED BY scripts/generate_unicode.py.\n')
f.write(' * DO NOT EDIT BY HAND.\n')
f.write(' */\n\n')
export_boundary_regex(f, "NFC")
f.write('\n')
export_boundary_regex(f, "NFD")
f.write('\n')
export_boundary_regex(f, "NFKC")
f.write('\n')
export_boundary_regex(f, "NFKD")
|
bistring/js/scripts/generate_unicode.py/0
|
{
"file_path": "bistring/js/scripts/generate_unicode.py",
"repo_id": "bistring",
"token_count": 812
}
| 383 |
[[source]]
name = "pypi"
url = "https://pypi.org/simple"
verify_ssl = true
[dev-packages]
bistring = {editable = true,extras = ["dev"],path = "."}
[packages]
bistring = {path = "."}
|
bistring/python/Pipfile/0
|
{
"file_path": "bistring/python/Pipfile",
"repo_id": "bistring",
"token_count": 78
}
| 384 |
from typing import Iterator, Tuple, Union, overload
UString = Union[str, 'UnicodeString']
class BreakIterator:
DONE: int
@classmethod
def createCharacterInstance(cls, locale: Locale) -> BreakIterator: ...
@classmethod
def createWordInstance(cls, locale: Locale) -> BreakIterator: ...
@classmethod
def createSentenceInstance(cls, locale: Locale) -> BreakIterator: ...
def setText(self, text: UString) -> None: ...
def first(self) -> int: ...
def nextBoundary(self) -> int: ...
def getRuleStatus(self) -> int: ...
class CaseMap:
@classmethod
def fold(cls, text: UString, edits: Edits) -> str: ...
@classmethod
def toLower(cls, locale: Locale, text: UString, edits: Edits) -> str: ...
@classmethod
def toUpper(cls, locale: Locale, text: UString, edits: Edits) -> str: ...
@classmethod
def toTitle(cls, locale: Locale, text: UString, edits: Edits) -> str: ...
class Edits:
def __init__(self) -> None: ...
def getFineIterator(self) -> Iterator[Tuple[bool, int, int, int, int, int]]: ...
class Locale:
def __init__(self, name: str): ...
class Normalizer2:
@classmethod
def getNFCInstance(cls) -> Normalizer2: ...
@classmethod
def getNFDInstance(cls) -> Normalizer2: ...
@classmethod
def getNFKCInstance(cls) -> Normalizer2: ...
@classmethod
def getNFKDInstance(cls) -> Normalizer2: ...
def normalize(self, text: UString) -> str: ...
def hasBoundaryBefore(self, c: UString) -> bool: ...
class UnicodeString:
def __init__(self, string: str): ...
@overload
def __getitem__(self, index: int) -> str: ...
@overload
def __getitem__(self, index: slice) -> UnicodeString: ...
def __len__(self) -> int: ...
@overload
def countChar32(self) -> int: ...
@overload
def countChar32(self, start: int, length: int) -> int: ...
def charAt(self, index: int) -> int: ...
def char32At(self, index: int) -> int: ...
|
bistring/python/stubs/icu.pyi/0
|
{
"file_path": "bistring/python/stubs/icu.pyi",
"repo_id": "bistring",
"token_count": 749
}
| 385 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import json
import os.path
from typing import List
from botbuilder.core import MessageFactory, TurnContext
from botbuilder.schema import Attachment, ChannelAccount
from helpers import DialogHelper
from .dialog_bot import DialogBot
class DialogAndWelcomeBot(DialogBot):
async def on_members_added_activity(
self, members_added: List[ChannelAccount], turn_context: TurnContext
):
for member in members_added:
# Greet anyone that was not the target (recipient) of this message.
# To learn more about Adaptive Cards, see https://aka.ms/msbot-adaptivecards for more details.
if member.id != turn_context.activity.recipient.id:
welcome_card = self.create_adaptive_card_attachment()
response = MessageFactory.attachment(welcome_card)
await turn_context.send_activity(response)
await DialogHelper.run_dialog(
self.dialog,
turn_context,
self.conversation_state.create_property("DialogState"),
)
# Load attachment from file.
def create_adaptive_card_attachment(self):
relative_path = os.path.abspath(os.path.dirname(__file__))
path = os.path.join(relative_path, "../cards/welcomeCard.json")
with open(path) as card_file:
card = json.load(card_file)
return Attachment(
content_type="application/vnd.microsoft.card.adaptive", content=card
)
|
botbuilder-python/generators/app/templates/core/{{cookiecutter.bot_name}}/bots/dialog_and_welcome_bot.py/0
|
{
"file_path": "botbuilder-python/generators/app/templates/core/{{cookiecutter.bot_name}}/bots/dialog_and_welcome_bot.py",
"repo_id": "botbuilder-python",
"token_count": 641
}
| 386 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from botbuilder.dialogs import WaterfallDialog, WaterfallStepContext, DialogTurnResult
from botbuilder.dialogs.prompts import ConfirmPrompt, TextPrompt, PromptOptions
from botbuilder.core import MessageFactory
from botbuilder.schema import InputHints
from datatypes_date_time.timex import Timex
from .cancel_and_help_dialog import CancelAndHelpDialog
from .date_resolver_dialog import DateResolverDialog
class BookingDialog(CancelAndHelpDialog):
def __init__(self, dialog_id: str = None):
super(BookingDialog, self).__init__(dialog_id or BookingDialog.__name__)
self.add_dialog(TextPrompt(TextPrompt.__name__))
self.add_dialog(ConfirmPrompt(ConfirmPrompt.__name__))
self.add_dialog(DateResolverDialog(DateResolverDialog.__name__))
self.add_dialog(
WaterfallDialog(
WaterfallDialog.__name__,
[
self.destination_step,
self.origin_step,
self.travel_date_step,
self.confirm_step,
self.final_step,
],
)
)
self.initial_dialog_id = WaterfallDialog.__name__
async def destination_step(
self, step_context: WaterfallStepContext
) -> DialogTurnResult:
"""
If a destination city has not been provided, prompt for one.
:param step_context:
:return DialogTurnResult:
"""
booking_details = step_context.options
if booking_details.destination is None:
message_text = "Where would you like to travel to?"
prompt_message = MessageFactory.text(
message_text, message_text, InputHints.expecting_input
)
return await step_context.prompt(
TextPrompt.__name__, PromptOptions(prompt=prompt_message)
)
return await step_context.next(booking_details.destination)
async def origin_step(self, step_context: WaterfallStepContext) -> DialogTurnResult:
"""
If an origin city has not been provided, prompt for one.
:param step_context:
:return DialogTurnResult:
"""
booking_details = step_context.options
# Capture the response to the previous step's prompt
booking_details.destination = step_context.result
if booking_details.origin is None:
message_text = "From what city will you be travelling?"
prompt_message = MessageFactory.text(
message_text, message_text, InputHints.expecting_input
)
return await step_context.prompt(
TextPrompt.__name__, PromptOptions(prompt=prompt_message)
)
return await step_context.next(booking_details.origin)
async def travel_date_step(
self, step_context: WaterfallStepContext
) -> DialogTurnResult:
"""
If a travel date has not been provided, prompt for one.
This will use the DATE_RESOLVER_DIALOG.
:param step_context:
:return DialogTurnResult:
"""
booking_details = step_context.options
# Capture the results of the previous step
booking_details.origin = step_context.result
if not booking_details.travel_date or self.is_ambiguous(
booking_details.travel_date
):
return await step_context.begin_dialog(
DateResolverDialog.__name__, booking_details.travel_date
)
return await step_context.next(booking_details.travel_date)
async def confirm_step(
self, step_context: WaterfallStepContext
) -> DialogTurnResult:
"""
Confirm the information the user has provided.
:param step_context:
:return DialogTurnResult:
"""
booking_details = step_context.options
# Capture the results of the previous step
booking_details.travel_date = step_context.result
message_text = (
f"Please confirm, I have you traveling to: { booking_details.destination } from: "
f"{ booking_details.origin } on: { booking_details.travel_date}."
)
prompt_message = MessageFactory.text(
message_text, message_text, InputHints.expecting_input
)
# Offer a YES/NO prompt.
return await step_context.prompt(
ConfirmPrompt.__name__, PromptOptions(prompt=prompt_message)
)
async def final_step(self, step_context: WaterfallStepContext) -> DialogTurnResult:
"""
Complete the interaction and end the dialog.
:param step_context:
:return DialogTurnResult:
"""
if step_context.result:
booking_details = step_context.options
return await step_context.end_dialog(booking_details)
return await step_context.end_dialog()
def is_ambiguous(self, timex: str) -> bool:
timex_property = Timex(timex)
return "definite" not in timex_property.types
|
botbuilder-python/generators/app/templates/core/{{cookiecutter.bot_name}}/dialogs/booking_dialog.py/0
|
{
"file_path": "botbuilder-python/generators/app/templates/core/{{cookiecutter.bot_name}}/dialogs/booking_dialog.py",
"repo_id": "botbuilder-python",
"token_count": 2167
}
| 387 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from botbuilder.core import ActivityHandler, TurnContext
from botbuilder.schema import ChannelAccount
class MyBot(ActivityHandler):
async def on_members_added_activity(
self,
members_added: ChannelAccount,
turn_context: TurnContext
):
for member_added in members_added:
if member_added.id != turn_context.activity.recipient.id:
await turn_context.send_activity("Hello world!")
|
botbuilder-python/generators/app/templates/empty/{{cookiecutter.bot_name}}/bot.py/0
|
{
"file_path": "botbuilder-python/generators/app/templates/empty/{{cookiecutter.bot_name}}/bot.py",
"repo_id": "botbuilder-python",
"token_count": 187
}
| 388 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from botbuilder.schema import ResourceResponse, ConversationAccount
class ActivityResourceResponse(ResourceResponse):
def __init__(self, activity_id: str, conversation: ConversationAccount, **kwargs):
super().__init__(**kwargs)
self.activity_id = activity_id
self.conversation = conversation
|
botbuilder-python/libraries/botbuilder-adapters-slack/botbuilder/adapters/slack/activity_resourceresponse.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-adapters-slack/botbuilder/adapters/slack/activity_resourceresponse.py",
"repo_id": "botbuilder-python",
"token_count": 121
}
| 389 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from typing import List
from botbuilder.dialogs import (
WaterfallDialog,
WaterfallStepContext,
DialogContext,
DialogTurnResult,
Dialog,
ObjectPath,
DialogTurnStatus,
DialogReason,
)
from botbuilder.schema import Activity, ActivityTypes
from .qnamaker_dialog_options import QnAMakerDialogOptions
from .. import (
QnAMakerOptions,
QnADialogResponseOptions,
QnAMaker,
QnAMakerEndpoint,
)
from ..models import QnARequestContext, Metadata, QueryResult, FeedbackRecord
from ..models.ranker_types import RankerTypes
from ..utils import QnACardBuilder
class QnAMakerDialog(WaterfallDialog):
"""
A dialog that supports multi-step and adaptive-learning QnA Maker services.
.. remarks::
An instance of this class targets a specific QnA Maker knowledge base.
It supports knowledge bases that include follow-up prompt and active learning features.
"""
KEY_QNA_CONTEXT_DATA = "qnaContextData"
"""
The path for storing and retrieving QnA Maker context data.
.. remarks:
This represents context about the current or previous call to QnA Maker.
It is stored within the current step's :class:'botbuilder.dialogs.WaterfallStepContext'.
It supports QnA Maker's follow-up prompt and active learning features.
"""
KEY_PREVIOUS_QNA_ID = "prevQnAId"
"""
The path for storing and retrieving the previous question ID.
.. remarks:
This represents the QnA question ID from the previous turn.
It is stored within the current step's :class:'botbuilder.dialogs.WaterfallStepContext'.
It supports QnA Maker's follow-up prompt and active learning features.
"""
KEY_OPTIONS = "options"
"""
The path for storing and retrieving the options for this instance of the dialog.
.. remarks:
This includes the options with which the dialog was started and options
expected by the QnA Maker service.
It is stored within the current step's :class:'botbuilder.dialogs.WaterfallStepContext'.
It supports QnA Maker and the dialog system.
"""
# Dialog Options parameters
DEFAULT_THRESHOLD = 0.3
""" The default threshold for answers returned, based on score. """
DEFAULT_TOP_N = 3
""" The default maximum number of answers to be returned for the question. """
DEFAULT_NO_ANSWER = "No QnAMaker answers found."
""" The default no answer text sent to the user. """
# Card parameters
DEFAULT_CARD_TITLE = "Did you mean:"
""" The default active learning card title. """
DEFAULT_CARD_NO_MATCH_TEXT = "None of the above."
""" The default active learning no match text. """
DEFAULT_CARD_NO_MATCH_RESPONSE = "Thanks for the feedback."
""" The default active learning response text. """
# Value Properties
PROPERTY_CURRENT_QUERY = "currentQuery"
PROPERTY_QNA_DATA = "qnaData"
def __init__(
self,
knowledgebase_id: str,
endpoint_key: str,
hostname: str,
no_answer: Activity = None,
threshold: float = DEFAULT_THRESHOLD,
active_learning_card_title: str = DEFAULT_CARD_TITLE,
card_no_match_text: str = DEFAULT_CARD_NO_MATCH_TEXT,
top: int = DEFAULT_TOP_N,
card_no_match_response: Activity = None,
strict_filters: [Metadata] = None,
dialog_id: str = "QnAMakerDialog",
):
"""
Initializes a new instance of the QnAMakerDialog class.
:param knowledgebase_id: The ID of the QnA Maker knowledge base to query.
:param endpoint_key: The QnA Maker endpoint key to use to query the knowledge base.
:param hostname: The QnA Maker host URL for the knowledge base, starting with "https://" and
ending with "/qnamaker".
:param no_answer: The activity to send the user when QnA Maker does not find an answer.
:param threshold: The threshold for answers returned, based on score.
:param active_learning_card_title: The card title to use when showing active learning options
to the user, if active learning is enabled.
:param card_no_match_text: The button text to use with active learning options,
allowing a user to indicate none of the options are applicable.
:param top: The maximum number of answers to return from the knowledge base.
:param card_no_match_response: The activity to send the user if they select the no match option
on an active learning card.
:param strict_filters: QnA Maker metadata with which to filter or boost queries to the
knowledge base; or null to apply none.
:param dialog_id: The ID of this dialog.
"""
super().__init__(dialog_id)
self.knowledgebase_id = knowledgebase_id
self.endpoint_key = endpoint_key
self.hostname = hostname
self.no_answer = no_answer
self.threshold = threshold
self.active_learning_card_title = active_learning_card_title
self.card_no_match_text = card_no_match_text
self.top = top
self.card_no_match_response = card_no_match_response
self.strict_filters = strict_filters
self.maximum_score_for_low_score_variation = 0.95
self.add_step(self.__call_generate_answer)
self.add_step(self.__call_train)
self.add_step(self.__check_for_multiturn_prompt)
self.add_step(self.__display_qna_result)
async def begin_dialog(
self, dialog_context: DialogContext, options: object = None
) -> DialogTurnResult:
"""
Called when the dialog is started and pushed onto the dialog stack.
.. remarks:
If the task is successful, the result indicates whether the dialog is still
active after the turn has been processed by the dialog.
:param dialog_context: The :class:'botbuilder.dialogs.DialogContext' for the current turn of conversation.
:param options: Optional, initial information to pass to the dialog.
"""
if not dialog_context:
raise TypeError("DialogContext is required")
if (
dialog_context.context
and dialog_context.context.activity
and dialog_context.context.activity.type != ActivityTypes.message
):
return Dialog.end_of_turn
dialog_options = QnAMakerDialogOptions(
options=self._get_qnamaker_options(dialog_context),
response_options=self._get_qna_response_options(dialog_context),
)
if options:
dialog_options = ObjectPath.assign(dialog_options, options)
ObjectPath.set_path_value(
dialog_context.active_dialog.state,
QnAMakerDialog.KEY_OPTIONS,
dialog_options,
)
return await super().begin_dialog(dialog_context, dialog_options)
def _get_qnamaker_client(self, dialog_context: DialogContext) -> QnAMaker:
"""
Gets a :class:'botbuilder.ai.qna.QnAMaker' to use to access the QnA Maker knowledge base.
:param dialog_context: The :class:'botbuilder.dialogs.DialogContext' for the current turn of conversation.
"""
endpoint = QnAMakerEndpoint(
endpoint_key=self.endpoint_key,
host=self.hostname,
knowledge_base_id=self.knowledgebase_id,
)
options = self._get_qnamaker_options(dialog_context)
return QnAMaker(endpoint, options)
def _get_qnamaker_options( # pylint: disable=unused-argument
self, dialog_context: DialogContext
) -> QnAMakerOptions:
"""
Gets the options for the QnAMaker client that the dialog will use to query the knowledge base.
:param dialog_context: The :class:'botbuilder.dialogs.DialogContext' for the current turn of conversation.
"""
return QnAMakerOptions(
score_threshold=self.threshold,
strict_filters=self.strict_filters,
top=self.top,
context=QnARequestContext(),
qna_id=0,
ranker_type=RankerTypes.DEFAULT,
is_test=False,
)
def _get_qna_response_options( # pylint: disable=unused-argument
self, dialog_context: DialogContext
) -> QnADialogResponseOptions:
"""
Gets the options the dialog will use to display query results to the user.
:param dialog_context: The :class:'botbuilder.dialogs.DialogContext' for the current turn of conversation.
"""
return QnADialogResponseOptions(
no_answer=self.no_answer,
active_learning_card_title=self.active_learning_card_title
or QnAMakerDialog.DEFAULT_CARD_TITLE,
card_no_match_text=self.card_no_match_text
or QnAMakerDialog.DEFAULT_CARD_NO_MATCH_TEXT,
card_no_match_response=self.card_no_match_response,
)
async def __call_generate_answer(self, step_context: WaterfallStepContext):
dialog_options: QnAMakerDialogOptions = ObjectPath.get_path_value(
step_context.active_dialog.state, QnAMakerDialog.KEY_OPTIONS
)
# Resetting context and QnAId
dialog_options.options.qna_id = 0
dialog_options.options.context = QnARequestContext()
# Storing the context info
step_context.values[
QnAMakerDialog.PROPERTY_CURRENT_QUERY
] = step_context.context.activity.text
# -Check if previous context is present, if yes then put it with the query
# -Check for id if query is present in reverse index.
previous_context_data = ObjectPath.get_path_value(
step_context.active_dialog.state, QnAMakerDialog.KEY_QNA_CONTEXT_DATA, {}
)
previous_qna_id = ObjectPath.get_path_value(
step_context.active_dialog.state, QnAMakerDialog.KEY_PREVIOUS_QNA_ID, 0
)
if previous_qna_id > 0:
dialog_options.options.context = QnARequestContext(
previous_qna_id=previous_qna_id
)
current_qna_id = previous_context_data.get(
step_context.context.activity.text
)
if current_qna_id:
dialog_options.options.qna_id = current_qna_id
# Calling QnAMaker to get response.
qna_client = self._get_qnamaker_client(step_context)
response = await qna_client.get_answers_raw(
step_context.context, dialog_options.options
)
is_active_learning_enabled = response.active_learning_enabled
step_context.values[QnAMakerDialog.PROPERTY_QNA_DATA] = response.answers
# Resetting previous query.
previous_qna_id = -1
ObjectPath.set_path_value(
step_context.active_dialog.state,
QnAMakerDialog.KEY_PREVIOUS_QNA_ID,
previous_qna_id,
)
# Check if active learning is enabled and send card
# maximum_score_for_low_score_variation is the score above which no need to check for feedback.
if (
response.answers
and response.answers[0].score <= self.maximum_score_for_low_score_variation
):
# Get filtered list of the response that support low score variation criteria.
response.answers = qna_client.get_low_score_variation(response.answers)
if len(response.answers) > 1 and is_active_learning_enabled:
suggested_questions = [qna.questions[0] for qna in response.answers]
message = QnACardBuilder.get_suggestions_card(
suggested_questions,
dialog_options.response_options.active_learning_card_title,
dialog_options.response_options.card_no_match_text,
)
await step_context.context.send_activity(message)
ObjectPath.set_path_value(
step_context.active_dialog.state,
QnAMakerDialog.KEY_OPTIONS,
dialog_options,
)
await qna_client.close()
return DialogTurnResult(DialogTurnStatus.Waiting)
# If card is not shown, move to next step with top qna response.
result = [response.answers[0]] if response.answers else []
step_context.values[QnAMakerDialog.PROPERTY_QNA_DATA] = result
ObjectPath.set_path_value(
step_context.active_dialog.state, QnAMakerDialog.KEY_OPTIONS, dialog_options
)
await qna_client.close()
return await step_context.next(result)
async def __call_train(self, step_context: WaterfallStepContext):
dialog_options: QnAMakerDialogOptions = ObjectPath.get_path_value(
step_context.active_dialog.state, QnAMakerDialog.KEY_OPTIONS
)
train_responses: [QueryResult] = step_context.values[
QnAMakerDialog.PROPERTY_QNA_DATA
]
current_query = step_context.values[QnAMakerDialog.PROPERTY_CURRENT_QUERY]
reply = step_context.context.activity.text
if len(train_responses) > 1:
qna_results = [
result for result in train_responses if result.questions[0] == reply
]
if qna_results:
qna_result = qna_results[0]
step_context.values[QnAMakerDialog.PROPERTY_QNA_DATA] = [qna_result]
feedback_records = [
FeedbackRecord(
user_id=step_context.context.activity.id,
user_question=current_query,
qna_id=qna_result.id,
)
]
# Call Active Learning Train API
qna_client = self._get_qnamaker_client(step_context)
await qna_client.call_train(feedback_records)
await qna_client.close()
return await step_context.next([qna_result])
if (
reply.lower()
== dialog_options.response_options.card_no_match_text.lower()
):
activity = dialog_options.response_options.card_no_match_response
if not activity:
await step_context.context.send_activity(
QnAMakerDialog.DEFAULT_CARD_NO_MATCH_RESPONSE
)
else:
await step_context.context.send_activity(activity)
return await step_context.end_dialog()
return await super().run_step(
step_context, index=0, reason=DialogReason.BeginCalled, result=None
)
return await step_context.next(step_context.result)
async def __check_for_multiturn_prompt(self, step_context: WaterfallStepContext):
dialog_options: QnAMakerDialogOptions = ObjectPath.get_path_value(
step_context.active_dialog.state, QnAMakerDialog.KEY_OPTIONS
)
response = step_context.result
if response and isinstance(response, List):
answer = response[0]
if answer.context and answer.context.prompts:
previous_context_data = ObjectPath.get_path_value(
step_context.active_dialog.state,
QnAMakerDialog.KEY_QNA_CONTEXT_DATA,
{},
)
for prompt in answer.context.prompts:
previous_context_data[prompt.display_text] = prompt.qna_id
ObjectPath.set_path_value(
step_context.active_dialog.state,
QnAMakerDialog.KEY_QNA_CONTEXT_DATA,
previous_context_data,
)
ObjectPath.set_path_value(
step_context.active_dialog.state,
QnAMakerDialog.KEY_PREVIOUS_QNA_ID,
answer.id,
)
ObjectPath.set_path_value(
step_context.active_dialog.state,
QnAMakerDialog.KEY_OPTIONS,
dialog_options,
)
# Get multi-turn prompts card activity.
message = QnACardBuilder.get_qna_prompts_card(
answer, dialog_options.response_options.card_no_match_text
)
await step_context.context.send_activity(message)
return DialogTurnResult(DialogTurnStatus.Waiting)
return await step_context.next(step_context.result)
async def __display_qna_result(self, step_context: WaterfallStepContext):
dialog_options: QnAMakerDialogOptions = ObjectPath.get_path_value(
step_context.active_dialog.state, QnAMakerDialog.KEY_OPTIONS
)
reply = step_context.context.activity.text
if reply.lower() == dialog_options.response_options.card_no_match_text.lower():
activity = dialog_options.response_options.card_no_match_response
if not activity:
await step_context.context.send_activity(
QnAMakerDialog.DEFAULT_CARD_NO_MATCH_RESPONSE
)
else:
await step_context.context.send_activity(activity)
return await step_context.end_dialog()
# If previous QnAId is present, replace the dialog
previous_qna_id = ObjectPath.get_path_value(
step_context.active_dialog.state, QnAMakerDialog.KEY_PREVIOUS_QNA_ID, 0
)
if previous_qna_id > 0:
return await super().run_step(
step_context, index=0, reason=DialogReason.BeginCalled, result=None
)
# If response is present then show that response, else default answer.
response = step_context.result
if response and isinstance(response, List):
await step_context.context.send_activity(response[0].answer)
else:
activity = dialog_options.response_options.no_answer
if not activity:
await step_context.context.send_activity(
QnAMakerDialog.DEFAULT_NO_ANSWER
)
else:
await step_context.context.send_activity(activity)
return await step_context.end_dialog()
|
botbuilder-python/libraries/botbuilder-ai/botbuilder/ai/qna/dialogs/qnamaker_dialog.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-ai/botbuilder/ai/qna/dialogs/qnamaker_dialog.py",
"repo_id": "botbuilder-python",
"token_count": 8025
}
| 390 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from botbuilder.schema import Activity
class QnADialogResponseOptions:
def __init__(
self,
active_learning_card_title: str = None,
card_no_match_text: str = None,
no_answer: Activity = None,
card_no_match_response: Activity = None,
):
self.active_learning_card_title = active_learning_card_title
self.card_no_match_text = card_no_match_text
self.no_answer = no_answer
self.card_no_match_response = card_no_match_response
|
botbuilder-python/libraries/botbuilder-ai/botbuilder/ai/qna/qna_dialog_response_options.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-ai/botbuilder/ai/qna/qna_dialog_response_options.py",
"repo_id": "botbuilder-python",
"token_count": 234
}
| 391 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import json
import unittest
from typing import List, Tuple
from uuid import uuid4
from botbuilder.ai.luis import LuisApplication
class LuisApplicationTest(unittest.TestCase):
endpoint: str = "https://westus.api.cognitive.microsoft.com"
def test_luis_application_construction(self) -> None:
model = LuisApplicationTest.get_valid_model()
self.assertIsNotNone(model)
construction_data: List[Tuple[str, str]] = [
(None, str(uuid4())),
("", str(uuid4())),
("0000", str(uuid4())),
(str(uuid4()), None),
(str(uuid4()), ""),
(str(uuid4()), "000"),
]
for app_id, key in construction_data:
with self.subTest(app_id=app_id, key=key):
with self.assertRaises(ValueError):
LuisApplication(app_id, key, LuisApplicationTest.endpoint)
luis_app = LuisApplication(
str(uuid4()), str(uuid4()), LuisApplicationTest.endpoint
)
self.assertEqual(LuisApplicationTest.endpoint, luis_app.endpoint)
@unittest.skip("revisit")
def test_luis_application_serialization(self) -> None:
model = LuisApplicationTest.get_valid_model()
serialized = json.dumps(model)
deserialized = json.loads(serialized)
self.assertIsNotNone(deserialized)
self.assertEqual(model, deserialized)
def test_list_application_from_luis_endpoint(self) -> None:
# Arrange
# Note this is NOT a real LUIS application ID nor a real LUIS subscription-key
# theses are GUIDs edited to look right to the parsing and validation code.
endpoint = (
"https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/"
"b31aeaf3-3511-495b-a07f-571fc873214b?verbose=true&timezoneOffset=-360"
"&subscription-key=048ec46dc58e495482b0c447cfdbd291&q="
)
# Act
app = LuisApplication.from_application_endpoint(endpoint)
# Assert
self.assertEqual("b31aeaf3-3511-495b-a07f-571fc873214b", app.application_id)
self.assertEqual("048ec46dc58e495482b0c447cfdbd291", app.endpoint_key)
self.assertEqual("https://westus.api.cognitive.microsoft.com", app.endpoint)
def test_list_application_from_luis_endpoint_bad_arguments(self) -> None:
application_endpoint_data: List[str] = [
"this.is.not.a.uri",
"https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/"
"b31aeaf3-3511-495b-a07f-571fc873214b?verbose=true&timezoneOffset=-360&q=",
"https://westus.api.cognitive.microsoft.com?"
"verbose=true&timezoneOffset=-360&subscription-key=048ec46dc58e495482b0c447cfdbd291&q=",
]
for application_endpoint in application_endpoint_data:
with self.subTest(application_endpoint=application_endpoint):
with self.assertRaises(ValueError):
LuisApplication.from_application_endpoint(application_endpoint)
@staticmethod
def get_valid_model() -> LuisApplication:
return LuisApplication(str(uuid4()), str(uuid4()), LuisApplicationTest.endpoint)
|
botbuilder-python/libraries/botbuilder-ai/tests/luis/luis_application_test.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-ai/tests/luis/luis_application_test.py",
"repo_id": "botbuilder-python",
"token_count": 1445
}
| 392 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""Telemetry processor for Django."""
import sys
from ..processor.telemetry_processor import TelemetryProcessor
from .bot_telemetry_middleware import retrieve_bot_body
class DjangoTelemetryProcessor(TelemetryProcessor):
def can_process(self) -> bool:
return self.detect_django()
def get_request_body(self) -> str:
if self.detect_django():
# Retrieve from Middleware cache
return retrieve_bot_body()
return None
@staticmethod
def detect_django() -> bool:
"""Detects if running in django."""
return "django" in sys.modules
|
botbuilder-python/libraries/botbuilder-applicationinsights/botbuilder/applicationinsights/django/django_telemetry_processor.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-applicationinsights/botbuilder/applicationinsights/django/django_telemetry_processor.py",
"repo_id": "botbuilder-python",
"token_count": 245
}
| 393 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from warnings import warn
from botbuilder.core import (
BotAdapter,
BotState,
Storage,
RegisterClassMiddleware,
UserState,
ConversationState,
AutoSaveStateMiddleware,
)
class AdapterExtensions:
@staticmethod
def use_storage(adapter: BotAdapter, storage: Storage) -> BotAdapter:
"""
Registers a storage layer with the adapter. The storage object will be available via the turn context's
`turn_state` property.
:param adapter: The BotAdapter on which to register the storage object.
:param storage: The Storage object to register.
:return: The BotAdapter
"""
return adapter.use(RegisterClassMiddleware(storage))
@staticmethod
def use_bot_state(
bot_adapter: BotAdapter, *bot_states: BotState, auto: bool = True
) -> BotAdapter:
"""
Registers bot state object into the TurnContext. The botstate will be available via the turn context.
:param bot_adapter: The BotAdapter on which to register the state objects.
:param bot_states: One or more BotState objects to register.
:return: The updated adapter.
"""
if not bot_states:
raise TypeError("At least one BotAdapter is required")
for bot_state in bot_states:
bot_adapter.use(
RegisterClassMiddleware(
bot_state, AdapterExtensions.fullname(bot_state)
)
)
if auto:
bot_adapter.use(AutoSaveStateMiddleware(bot_states))
return bot_adapter
@staticmethod
def fullname(obj):
module = obj.__class__.__module__
if module is None or module == str.__class__.__module__:
return obj.__class__.__name__ # Avoid reporting __builtin__
return module + "." + obj.__class__.__name__
@staticmethod
def use_state(
adapter: BotAdapter,
user_state: UserState,
conversation_state: ConversationState,
auto: bool = True,
) -> BotAdapter:
"""
[DEPRECATED] Registers user and conversation state objects with the adapter. These objects will be available via
the turn context's `turn_state` property.
:param adapter: The BotAdapter on which to register the state objects.
:param user_state: The UserState object to register.
:param conversation_state: The ConversationState object to register.
:param auto: True to automatically persist state each turn.
:return: The BotAdapter
"""
warn(
"This method is deprecated in 4.9. You should use the method .use_bot_state() instead.",
DeprecationWarning,
)
if not adapter:
raise TypeError("BotAdapter is required")
if not user_state:
raise TypeError("UserState is required")
if not conversation_state:
raise TypeError("ConversationState is required")
adapter.use(RegisterClassMiddleware(user_state))
adapter.use(RegisterClassMiddleware(conversation_state))
if auto:
adapter.use(AutoSaveStateMiddleware([user_state, conversation_state]))
return adapter
|
botbuilder-python/libraries/botbuilder-core/botbuilder/core/adapter_extensions.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-core/botbuilder/core/adapter_extensions.py",
"repo_id": "botbuilder-python",
"token_count": 1278
}
| 394 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import uuid
from botbuilder.schema import (
Activity,
ActivityEventNames,
ActivityTypes,
ConversationReference,
)
def get_continuation_activity(reference: ConversationReference) -> Activity:
return Activity(
type=ActivityTypes.event,
name=ActivityEventNames.continue_conversation,
id=str(uuid.uuid1()),
channel_id=reference.channel_id,
service_url=reference.service_url,
conversation=reference.conversation,
recipient=reference.bot,
from_property=reference.user,
relates_to=reference,
)
|
botbuilder-python/libraries/botbuilder-core/botbuilder/core/conversation_reference_extension.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-core/botbuilder/core/conversation_reference_extension.py",
"repo_id": "botbuilder-python",
"token_count": 245
}
| 395 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from typing import List, Union
from botbuilder.schema import (
ActivityTypes,
Activity,
Attachment,
AttachmentLayoutTypes,
CardAction,
SuggestedActions,
InputHints,
)
def attachment_activity(
attachment_layout: AttachmentLayoutTypes,
attachments: List[Attachment],
text: str = None,
speak: str = None,
input_hint: Union[InputHints, str] = InputHints.accepting_input,
) -> Activity:
message = Activity(
type=ActivityTypes.message,
attachment_layout=attachment_layout,
attachments=attachments,
input_hint=input_hint,
)
if text:
message.text = text
if speak:
message.speak = speak
return message
class MessageFactory:
"""
A set of utility functions designed to assist with the formatting of the various message types a
bot can return.
"""
@staticmethod
def text(
text: str,
speak: str = None,
input_hint: Union[InputHints, str] = InputHints.accepting_input,
) -> Activity:
"""
Returns a simple text message.
:Example:
message = MessageFactory.text('Greetings from example message')
await context.send_activity(message)
:param text:
:param speak:
:param input_hint:
:return:
"""
message = Activity(type=ActivityTypes.message, text=text, input_hint=input_hint)
if speak:
message.speak = speak
return message
@staticmethod
def suggested_actions(
actions: List[CardAction],
text: str = None,
speak: str = None,
input_hint: Union[InputHints, str] = InputHints.accepting_input,
) -> Activity:
"""
Returns a message that includes a set of suggested actions and optional text.
:Example:
message = MessageFactory.suggested_actions([CardAction(title='a', type=ActionTypes.im_back, value='a'),
CardAction(title='b', type=ActionTypes.im_back, value='b'),
CardAction(title='c', type=ActionTypes.im_back, value='c')],
'Choose a color')
await context.send_activity(message)
:param actions:
:param text:
:param speak:
:param input_hint:
:return:
"""
actions = SuggestedActions(actions=actions)
message = Activity(
type=ActivityTypes.message, input_hint=input_hint, suggested_actions=actions
)
if text:
message.text = text
if speak:
message.speak = speak
return message
@staticmethod
def attachment(
attachment: Attachment,
text: str = None,
speak: str = None,
input_hint: Union[InputHints, str] = None,
):
"""
Returns a single message activity containing an attachment.
:Example:
message = MessageFactory.attachment(CardFactory.hero_card(HeroCard(title='White T-Shirt',
images=[CardImage(url=
'https://example.com/whiteShirt.jpg'
)],
buttons=[CardAction(title='buy')])))
await context.send_activity(message)
:param attachment:
:param text:
:param speak:
:param input_hint:
:return:
"""
return attachment_activity(
AttachmentLayoutTypes.list, [attachment], text, speak, input_hint
)
@staticmethod
def list(
attachments: List[Attachment],
text: str = None,
speak: str = None,
input_hint: Union[InputHints, str] = None,
) -> Activity:
"""
Returns a message that will display a set of attachments in list form.
:Example:
message = MessageFactory.list([CardFactory.hero_card(HeroCard(title='title1',
images=[CardImage(url='imageUrl1')],
buttons=[CardAction(title='button1')])),
CardFactory.hero_card(HeroCard(title='title2',
images=[CardImage(url='imageUrl2')],
buttons=[CardAction(title='button2')])),
CardFactory.hero_card(HeroCard(title='title3',
images=[CardImage(url='imageUrl3')],
buttons=[CardAction(title='button3')]))])
await context.send_activity(message)
:param attachments:
:param text:
:param speak:
:param input_hint:
:return:
"""
return attachment_activity(
AttachmentLayoutTypes.list, attachments, text, speak, input_hint
)
@staticmethod
def carousel(
attachments: List[Attachment],
text: str = None,
speak: str = None,
input_hint: Union[InputHints, str] = None,
) -> Activity:
"""
Returns a message that will display a set of attachments using a carousel layout.
:Example:
message = MessageFactory.carousel([CardFactory.hero_card(HeroCard(title='title1',
images=[CardImage(url='imageUrl1')],
buttons=[CardAction(title='button1')])),
CardFactory.hero_card(HeroCard(title='title2',
images=[CardImage(url='imageUrl2')],
buttons=[CardAction(title='button2')])),
CardFactory.hero_card(HeroCard(title='title3',
images=[CardImage(url='imageUrl3')],
buttons=[CardAction(title='button3')]))])
await context.send_activity(message)
:param attachments:
:param text:
:param speak:
:param input_hint:
:return:
"""
return attachment_activity(
AttachmentLayoutTypes.carousel, attachments, text, speak, input_hint
)
@staticmethod
def content_url(
url: str,
content_type: str,
name: str = None,
text: str = None,
speak: str = None,
input_hint: Union[InputHints, str] = None,
):
"""
Returns a message that will display a single image or video to a user.
:Example:
message = MessageFactory.content_url('https://example.com/hawaii.jpg', 'image/jpeg',
'Hawaii Trip', 'A photo from our family vacation.')
await context.send_activity(message)
:param url:
:param content_type:
:param name:
:param text:
:param speak:
:param input_hint:
:return:
"""
attachment = Attachment(content_type=content_type, content_url=url)
if name:
attachment.name = name
return attachment_activity(
AttachmentLayoutTypes.list, [attachment], text, speak, input_hint
)
|
botbuilder-python/libraries/botbuilder-core/botbuilder/core/message_factory.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-core/botbuilder/core/message_factory.py",
"repo_id": "botbuilder-python",
"token_count": 4031
}
| 396 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
from .bot_framework_skill import BotFrameworkSkill
from .bot_framework_client import BotFrameworkClient
from .conversation_id_factory import ConversationIdFactoryBase
from .skill_handler import SkillHandler
from .skill_conversation_id_factory import SkillConversationIdFactory
from .skill_conversation_id_factory_options import SkillConversationIdFactoryOptions
from .skill_conversation_reference import SkillConversationReference
__all__ = [
"BotFrameworkSkill",
"BotFrameworkClient",
"ConversationIdFactoryBase",
"SkillConversationIdFactory",
"SkillConversationIdFactoryOptions",
"SkillConversationReference",
"SkillHandler",
]
|
botbuilder-python/libraries/botbuilder-core/botbuilder/core/skills/__init__.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-core/botbuilder/core/skills/__init__.py",
"repo_id": "botbuilder-python",
"token_count": 246
}
| 397 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from http import HTTPStatus
from logging import Logger
from typing import Any
from msrest.universal_http import ClientRequest
from msrest.universal_http.async_abc import AsyncClientResponse
from msrest.universal_http.async_requests import (
AsyncRequestsHTTPSender as AsyncRequestsHTTPDriver,
)
from botframework.streaming import StreamingRequest, ReceiveResponse
from .streaming_request_handler import StreamingRequestHandler
class StreamingProtocolClientResponse(AsyncClientResponse):
def __init__(
self, request: StreamingRequest, streaming_response: ReceiveResponse
) -> None:
super(StreamingProtocolClientResponse, self).__init__(
request, streaming_response
)
# https://aiohttp.readthedocs.io/en/stable/client_reference.html#aiohttp.ClientResponse
self.status_code = streaming_response.status_code
# self.headers = streaming_response.headers
# self.reason = streaming_response.reason
self._body = None
def body(self) -> bytes:
"""Return the whole body as bytes in memory."""
if not self._body:
return bytes([])
return self._body
async def load_body(self) -> None:
"""Load in memory the body, so it could be accessible from sync methods."""
self._body: ReceiveResponse
self._body = self.internal_response.read_body()
def raise_for_status(self):
if 400 <= self.internal_response.status_code <= 599:
raise Exception(f"Http error: {self.internal_response.status_code}")
class StreamingHttpDriver(AsyncRequestsHTTPDriver):
def __init__(
self,
request_handler: StreamingRequestHandler,
*,
config=None,
logger: Logger = None,
):
super().__init__(config)
if not request_handler:
raise TypeError(
f"'request_handler: {request_handler.__class__.__name__}' argument can't be None"
)
self._request_handler = request_handler
self._logger = logger
async def send(
self, request: ClientRequest, **config: Any # pylint: disable=unused-argument
) -> AsyncClientResponse:
# TODO: validate form of request to perform operations
streaming_request = StreamingRequest(
path=request.url[request.url.index("v3/") :], verb=request.method
)
streaming_request.set_body(request.data)
return await self._send_request(streaming_request)
async def _send_request(
self, request: StreamingRequest
) -> StreamingProtocolClientResponse:
try:
server_response = await self._request_handler.send_streaming_request(
request
)
if not server_response:
raise Exception("Server response from streaming request is None")
if server_response.status_code == HTTPStatus.OK:
# TODO: this should be an object read from json
return StreamingProtocolClientResponse(request, server_response)
except Exception as error:
# TODO: log error
raise error
return None
|
botbuilder-python/libraries/botbuilder-core/botbuilder/core/streaming/streaming_http_client.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-core/botbuilder/core/streaming/streaming_http_client.py",
"repo_id": "botbuilder-python",
"token_count": 1248
}
| 398 |
[bdist_wheel]
universal=0
|
botbuilder-python/libraries/botbuilder-core/setup.cfg/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-core/setup.cfg",
"repo_id": "botbuilder-python",
"token_count": 10
}
| 399 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import uuid
from typing import List
import aiounittest
from botbuilder.core import TurnContext
from botbuilder.core.adapters import TestAdapter
from botbuilder.schema import (
Activity,
ConversationAccount,
ConversationReference,
ChannelAccount,
)
from simple_adapter import SimpleAdapter
from call_counting_middleware import CallCountingMiddleware
from test_message import TestMessage
class TestBotAdapter(aiounittest.AsyncTestCase):
def test_adapter_single_use(self):
adapter = SimpleAdapter()
adapter.use(CallCountingMiddleware())
def test_adapter_use_chaining(self):
adapter = SimpleAdapter()
adapter.use(CallCountingMiddleware()).use(CallCountingMiddleware())
async def test_pass_resource_responses_through(self):
def validate_responses( # pylint: disable=unused-argument
activities: List[Activity],
):
pass # no need to do anything.
adapter = SimpleAdapter(call_on_send=validate_responses)
context = TurnContext(adapter, Activity())
activity_id = str(uuid.uuid1())
activity = TestMessage.message(activity_id)
resource_response = await context.send_activity(activity)
self.assertTrue(
resource_response.id != activity_id, "Incorrect response Id returned"
)
async def test_continue_conversation_direct_msg(self):
callback_invoked = False
adapter = TestAdapter()
reference = ConversationReference(
activity_id="activityId",
bot=ChannelAccount(id="channelId", name="testChannelAccount", role="bot"),
channel_id="testChannel",
service_url="testUrl",
conversation=ConversationAccount(
conversation_type="",
id="testConversationId",
is_group=False,
name="testConversationName",
role="user",
),
user=ChannelAccount(id="channelId", name="testChannelAccount", role="bot"),
)
async def continue_callback(turn_context): # pylint: disable=unused-argument
nonlocal callback_invoked
callback_invoked = True
await adapter.continue_conversation(reference, continue_callback, "MyBot")
self.assertTrue(callback_invoked)
async def test_turn_error(self):
async def on_error(turn_context: TurnContext, err: Exception):
nonlocal self
self.assertIsNotNone(turn_context, "turn_context not found.")
self.assertIsNotNone(err, "error not found.")
self.assertEqual(err.__class__, Exception, "unexpected error thrown.")
adapter = SimpleAdapter()
adapter.on_turn_error = on_error
def handler(context: TurnContext): # pylint: disable=unused-argument
raise Exception
await adapter.process_request(TestMessage.message(), handler)
|
botbuilder-python/libraries/botbuilder-core/tests/test_bot_adapter.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-core/tests/test_bot_adapter.py",
"repo_id": "botbuilder-python",
"token_count": 1181
}
| 400 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import aiounittest
from botbuilder.core import (
MemoryTranscriptStore,
TranscriptLoggerMiddleware,
TurnContext,
)
from botbuilder.core.adapters import TestAdapter, TestFlow
from botbuilder.schema import Activity, ActivityEventNames, ActivityTypes
class TestTranscriptLoggerMiddleware(aiounittest.AsyncTestCase):
async def test_should_not_log_continue_conversation(self):
transcript_store = MemoryTranscriptStore()
conversation_id = ""
sut = TranscriptLoggerMiddleware(transcript_store)
async def aux_logic(context: TurnContext):
nonlocal conversation_id
conversation_id = context.activity.conversation.id
adapter = TestAdapter(aux_logic)
adapter.use(sut)
continue_conversation_activity = Activity(
type=ActivityTypes.event, name=ActivityEventNames.continue_conversation
)
test_flow = TestFlow(None, adapter)
step1 = await test_flow.send("foo")
step2 = await step1.send("bar")
await step2.send(continue_conversation_activity)
paged_result = await transcript_store.get_transcript_activities(
"test", conversation_id
)
self.assertEqual(
len(paged_result.items),
2,
"only the two message activities should be logged",
)
|
botbuilder-python/libraries/botbuilder-core/tests/test_transcript_logger_middleware.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-core/tests/test_transcript_logger_middleware.py",
"repo_id": "botbuilder-python",
"token_count": 556
}
| 401 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from typing import Callable, List
from .token import Token
class FindValuesOptions:
"""Contains search options, used to control how choices are recognized in a user's utterance."""
def __init__(
self,
allow_partial_matches: bool = None,
locale: str = None,
max_token_distance: int = None,
tokenizer: Callable[[str, str], List[Token]] = None,
):
"""
Parameters:
----------
allow_partial_matches: (Optional) If `True`, then only some of the tokens in a value need to exist to
be considered
a match. The default value is `False`.
locale: (Optional) locale/culture code of the utterance. Default is `en-US`.
max_token_distance: (Optional) maximum tokens allowed between two matched tokens in the utterance. So with
a max distance of 2 the value "second last" would match the utterance "second from the last"
but it wouldn't match "Wait a second. That's not the last one is it?".
The default value is "2".
tokenizer: (Optional) Tokenizer to use when parsing the utterance and values being recognized.
"""
self.allow_partial_matches = allow_partial_matches
self.locale = locale
self.max_token_distance = max_token_distance
self.tokenizer = tokenizer
|
botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/find_values_options.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/find_values_options.py",
"repo_id": "botbuilder-python",
"token_count": 504
}
| 402 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from datetime import datetime, timedelta
from threading import Lock
from warnings import warn
from botbuilder.core import (
BotAdapter,
BotStateSet,
ConversationState,
UserState,
TurnContext,
)
from botbuilder.core.skills import SkillConversationReference, SkillHandler
from botbuilder.dialogs.memory import DialogStateManagerConfiguration
from botbuilder.schema import Activity, ActivityTypes, EndOfConversationCodes
from botframework.connector.auth import (
AuthenticationConstants,
ClaimsIdentity,
GovernmentConstants,
SkillValidation,
)
from .dialog import Dialog
from .dialog_context import DialogContext
from .dialog_events import DialogEvents
from .dialog_extensions import DialogExtensions
from .dialog_set import DialogSet
from .dialog_state import DialogState
from .dialog_manager_result import DialogManagerResult
from .dialog_turn_status import DialogTurnStatus
from .dialog_turn_result import DialogTurnResult
class DialogManager:
"""
Class which runs the dialog system.
"""
def __init__(self, root_dialog: Dialog = None, dialog_state_property: str = None):
"""
Initializes a instance of the <see cref="DialogManager"/> class.
:param root_dialog: Root dialog to use.
:param dialog_state_property: alternate name for the dialog_state property. (Default is "DialogState").
"""
self.last_access = "_lastAccess"
self._root_dialog_id = ""
self._dialog_state_property = dialog_state_property or "DialogState"
self._lock = Lock()
# Gets or sets root dialog to use to start conversation.
self.root_dialog = root_dialog
# Gets or sets the ConversationState.
self.conversation_state: ConversationState = None
# Gets or sets the UserState.
self.user_state: UserState = None
# Gets InitialTurnState collection to copy into the TurnState on every turn.
self.initial_turn_state = {}
# Gets or sets global dialogs that you want to have be callable.
self.dialogs = DialogSet()
# Gets or sets the DialogStateManagerConfiguration.
self.state_configuration: DialogStateManagerConfiguration = None
# Gets or sets (optional) number of milliseconds to expire the bot's state after.
self.expire_after: int = None
async def on_turn(self, context: TurnContext) -> DialogManagerResult:
"""
Runs dialog system in the context of an ITurnContext.
:param context: turn context.
:return:
"""
# pylint: disable=too-many-statements
# Lazy initialize RootDialog so it can refer to assets like LG function templates
if not self._root_dialog_id:
with self._lock:
if not self._root_dialog_id:
self._root_dialog_id = self.root_dialog.id
# self.dialogs = self.root_dialog.telemetry_client
self.dialogs.add(self.root_dialog)
bot_state_set = BotStateSet([])
# Preload TurnState with DM TurnState.
for key, val in self.initial_turn_state.items():
context.turn_state[key] = val
# register DialogManager with TurnState.
context.turn_state[DialogManager.__name__] = self
conversation_state_name = ConversationState.__name__
if self.conversation_state is None:
if conversation_state_name not in context.turn_state:
raise Exception(
f"Unable to get an instance of {conversation_state_name} from turn_context."
)
self.conversation_state: ConversationState = context.turn_state[
conversation_state_name
]
else:
context.turn_state[conversation_state_name] = self.conversation_state
bot_state_set.add(self.conversation_state)
user_state_name = UserState.__name__
if self.user_state is None:
self.user_state = context.turn_state.get(user_state_name, None)
else:
context.turn_state[user_state_name] = self.user_state
if self.user_state is not None:
self.user_state: UserState = self.user_state
bot_state_set.add(self.user_state)
# create property accessors
# DateTime(last_access)
last_access_property = self.conversation_state.create_property(self.last_access)
last_access: datetime = await last_access_property.get(context, datetime.now)
# Check for expired conversation
if self.expire_after is not None and (
datetime.now() - last_access
) >= timedelta(milliseconds=float(self.expire_after)):
# Clear conversation state
await self.conversation_state.clear_state(context)
last_access = datetime.now()
await last_access_property.set(context, last_access)
# get dialog stack
dialogs_property = self.conversation_state.create_property(
self._dialog_state_property
)
dialog_state: DialogState = await dialogs_property.get(context, DialogState)
# Create DialogContext
dialog_context = DialogContext(self.dialogs, context, dialog_state)
# Call the common dialog "continue/begin" execution pattern shared with the classic RunAsync extension method
turn_result = (
await DialogExtensions._internal_run( # pylint: disable=protected-access
context, self._root_dialog_id, dialog_context
)
)
# save BotState changes
await bot_state_set.save_all_changes(dialog_context.context, False)
return DialogManagerResult(turn_result=turn_result)
@staticmethod
async def send_state_snapshot_trace(
dialog_context: DialogContext,
trace_label: str = None, # pylint: disable=unused-argument
):
"""
Helper to send a trace activity with a memory snapshot of the active dialog DC.
:param dialog_context:
:param trace_label:
:return:
"""
warn(
"This method will be deprecated as no longer is necesary",
PendingDeprecationWarning,
)
await DialogExtensions._send_state_snapshot_trace( # pylint: disable=protected-access
dialog_context
)
@staticmethod
def is_from_parent_to_skill(turn_context: TurnContext) -> bool:
if turn_context.turn_state.get(
SkillHandler.SKILL_CONVERSATION_REFERENCE_KEY, None
):
return False
claims_identity: ClaimsIdentity = turn_context.turn_state.get(
BotAdapter.BOT_IDENTITY_KEY, None
)
return isinstance(
claims_identity, ClaimsIdentity
) and SkillValidation.is_skill_claim(claims_identity.claims)
# Recursively walk up the DC stack to find the active DC.
@staticmethod
def get_active_dialog_context(dialog_context: DialogContext) -> DialogContext:
"""
Recursively walk up the DC stack to find the active DC.
:param dialog_context:
:return:
"""
warn(
"This method will be deprecated as no longer is necesary",
PendingDeprecationWarning,
)
return DialogExtensions._get_active_dialog_context( # pylint: disable=protected-access
dialog_context
)
@staticmethod
def should_send_end_of_conversation_to_parent(
context: TurnContext, turn_result: DialogTurnResult
) -> bool:
"""
Helper to determine if we should send an EndOfConversation to the parent or not.
:param context:
:param turn_result:
:return:
"""
if not (
turn_result.status == DialogTurnStatus.Complete
or turn_result.status == DialogTurnStatus.Cancelled
):
# The dialog is still going, don't return EoC.
return False
claims_identity: ClaimsIdentity = context.turn_state.get(
BotAdapter.BOT_IDENTITY_KEY, None
)
if isinstance(
claims_identity, ClaimsIdentity
) and SkillValidation.is_skill_claim(claims_identity.claims):
# EoC Activities returned by skills are bounced back to the bot by SkillHandler.
# In those cases we will have a SkillConversationReference instance in state.
skill_conversation_reference: SkillConversationReference = (
context.turn_state.get(SkillHandler.SKILL_CONVERSATION_REFERENCE_KEY)
)
if skill_conversation_reference:
# If the skill_conversation_reference.OAuthScope is for one of the supported channels, we are at the
# root and we should not send an EoC.
return skill_conversation_reference.oauth_scope not in (
AuthenticationConstants.TO_CHANNEL_FROM_BOT_OAUTH_SCOPE,
GovernmentConstants.TO_CHANNEL_FROM_BOT_OAUTH_SCOPE,
)
return True
return False
async def handle_skill_on_turn(
self, dialog_context: DialogContext
) -> DialogTurnResult:
warn(
"This method will be deprecated as no longer is necesary",
PendingDeprecationWarning,
)
# the bot is running as a skill.
turn_context = dialog_context.context
# Process remote cancellation
if (
turn_context.activity.type == ActivityTypes.end_of_conversation
and dialog_context.active_dialog is not None
and self.is_from_parent_to_skill(turn_context)
):
# Handle remote cancellation request from parent.
active_dialog_context = self.get_active_dialog_context(dialog_context)
# Send cancellation message to the top dialog in the stack to ensure all the parents are canceled in the
# right order.
return await active_dialog_context.cancel_all_dialogs(True)
# Handle reprompt
# Process a reprompt event sent from the parent.
if (
turn_context.activity.type == ActivityTypes.event
and turn_context.activity.name == DialogEvents.reprompt_dialog
):
if not dialog_context.active_dialog:
return DialogTurnResult(DialogTurnStatus.Empty)
await dialog_context.reprompt_dialog()
return DialogTurnResult(DialogTurnStatus.Waiting)
# Continue execution
# - This will apply any queued up interruptions and execute the current/next step(s).
turn_result = await dialog_context.continue_dialog()
if turn_result.status == DialogTurnStatus.Empty:
# restart root dialog
turn_result = await dialog_context.begin_dialog(self._root_dialog_id)
await DialogManager.send_state_snapshot_trace(dialog_context, "Skill State")
if self.should_send_end_of_conversation_to_parent(turn_context, turn_result):
# Send End of conversation at the end.
activity = Activity(
type=ActivityTypes.end_of_conversation,
value=turn_result.result,
locale=turn_context.activity.locale,
code=EndOfConversationCodes.completed_successfully
if turn_result.status == DialogTurnStatus.Complete
else EndOfConversationCodes.user_cancelled,
)
await turn_context.send_activity(activity)
return turn_result
async def handle_bot_on_turn(
self, dialog_context: DialogContext
) -> DialogTurnResult:
warn(
"This method will be deprecated as no longer is necesary",
PendingDeprecationWarning,
)
# the bot is running as a root bot.
if dialog_context.active_dialog is None:
# start root dialog
turn_result = await dialog_context.begin_dialog(self._root_dialog_id)
else:
# Continue execution
# - This will apply any queued up interruptions and execute the current/next step(s).
turn_result = await dialog_context.continue_dialog()
if turn_result.status == DialogTurnStatus.Empty:
# restart root dialog
turn_result = await dialog_context.begin_dialog(self._root_dialog_id)
await self.send_state_snapshot_trace(dialog_context, "Bot State")
return turn_result
|
botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/dialog_manager.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/dialog_manager.py",
"repo_id": "botbuilder-python",
"token_count": 5215
}
| 403 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from botbuilder.dialogs.memory import PathResolverBase
class AliasPathResolver(PathResolverBase):
def __init__(self, alias: str, prefix: str, postfix: str = None):
"""
Initializes a new instance of the <see cref="AliasPathResolver"/> class.
<param name="alias">Alias name.</param>
<param name="prefix">Prefix name.</param>
<param name="postfix">Postfix name.</param>
"""
if alias is None:
raise TypeError(f"Expecting: alias, but received None")
if prefix is None:
raise TypeError(f"Expecting: prefix, but received None")
# Gets the alias name.
self.alias = alias.strip()
self._prefix = prefix.strip()
self._postfix = postfix.strip() if postfix else ""
def transform_path(self, path: str):
"""
Transforms the path.
<param name="path">Path to inspect.</param>
<returns>Transformed path.</returns>
"""
if not path:
raise TypeError(f"Expecting: path, but received None")
path = path.strip()
if (
path.startswith(self.alias)
and len(path) > len(self.alias)
and AliasPathResolver._is_path_char(path[len(self.alias)])
):
# here we only deals with trailing alias, alias in middle be handled in further breakdown
# $xxx -> path.xxx
return f"{self._prefix}{path[len(self.alias):]}{self._postfix}".rstrip(".")
return path
@staticmethod
def _is_path_char(char: str) -> bool:
"""
Verifies if a character is valid for a path.
<param name="ch">Character to verify.</param>
<returns><c>true</c> if the character is valid for a path otherwise, <c>false</c>.</returns>
"""
return len(char) == 1 and (char.isalpha() or char == "_")
|
botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/memory/path_resolvers/alias_path_resolver.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/memory/path_resolvers/alias_path_resolver.py",
"repo_id": "botbuilder-python",
"token_count": 814
}
| 404 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from botbuilder.dialogs.memory import scope_path
from .memory_scope import MemoryScope
class ThisMemoryScope(MemoryScope):
def __init__(self):
super().__init__(scope_path.THIS)
def get_memory(self, dialog_context: "DialogContext") -> object:
if not dialog_context:
raise TypeError(f"Expecting: DialogContext, but received None")
return (
dialog_context.active_dialog.state if dialog_context.active_dialog else None
)
def set_memory(self, dialog_context: "DialogContext", memory: object):
if not dialog_context:
raise TypeError(f"Expecting: DialogContext, but received None")
if not memory:
raise TypeError(f"Expecting: object, but received None")
dialog_context.active_dialog.state = memory
|
botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/memory/scopes/this_memory_scope.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/memory/scopes/this_memory_scope.py",
"repo_id": "botbuilder-python",
"token_count": 328
}
| 405 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from abc import abstractmethod
import copy
from typing import Dict, List
from botbuilder.core.turn_context import TurnContext
from botbuilder.schema import InputHints, ActivityTypes
from botbuilder.dialogs.choices import (
Choice,
ChoiceFactory,
ChoiceFactoryOptions,
ListStyle,
)
from botbuilder.schema import Activity
from .prompt_options import PromptOptions
from .prompt_validator_context import PromptValidatorContext
from ..dialog_reason import DialogReason
from ..dialog import Dialog
from ..dialog_instance import DialogInstance
from ..dialog_turn_result import DialogTurnResult
from ..dialog_context import DialogContext
class Prompt(Dialog):
"""
Defines the core behavior of prompt dialogs. Extends the :class:`Dialog` base class.
.. remarks::
When the prompt ends, it returns an object that represents the value it was prompted for.
Use :meth:`DialogSet.add()` or :meth:`ComponentDialog.add_dialog()` to add a prompt to
a dialog set or component dialog, respectively.
Use :meth:`DialogContext.prompt()` or :meth:`DialogContext.begin_dialog()` to start the prompt.
If you start a prompt from a :class:`WaterfallStep` in a :class:`WaterfallDialog`, then the
prompt result will be available in the next step of the waterfall.
"""
ATTEMPT_COUNT_KEY = "AttemptCount"
persisted_options = "options"
persisted_state = "state"
def __init__(self, dialog_id: str, validator: object = None):
"""
Creates a new :class:`Prompt` instance.
:param dialog_id: Unique Id of the prompt within its parent :class:`DialogSet`
:class:`ComponentDialog`
:type dialog_id: str
:param validator: Optionally provide additional validation and re-prompting logic
:type validator: Object
"""
super(Prompt, self).__init__(dialog_id)
self._validator = validator
async def begin_dialog(
self, dialog_context: DialogContext, options: object = None
) -> DialogTurnResult:
"""
Starts a prompt dialog. Called when a prompt dialog is pushed onto the dialog stack and is being activated.
:param dialog_context: The dialog context for the current turn of the conversation
:type dialog_context: :class:`DialogContext`
:param options: Optional, additional information to pass to the prompt being started
:type options: Object
:return: The dialog turn result
:rtype: :class:`DialogTurnResult`
.. note::
The result indicates whether the prompt is still active after the turn has been processed.
"""
if not dialog_context:
raise TypeError("Prompt(): dc cannot be None.")
if not isinstance(options, PromptOptions):
raise TypeError("Prompt(): Prompt options are required for Prompt dialogs.")
# Ensure prompts have input hint set
if options.prompt is not None and not options.prompt.input_hint:
options.prompt.input_hint = InputHints.expecting_input
if options.retry_prompt is not None and not options.retry_prompt.input_hint:
options.retry_prompt.input_hint = InputHints.expecting_input
# Initialize prompt state
state = dialog_context.active_dialog.state
state[self.persisted_options] = options
state[self.persisted_state] = {}
# Send initial prompt
await self.on_prompt(
dialog_context.context,
state[self.persisted_state],
state[self.persisted_options],
False,
)
return Dialog.end_of_turn
async def continue_dialog(self, dialog_context: DialogContext):
"""
Continues a dialog.
:param dialog_context: The dialog context for the current turn of the conversation
:type dialog_context: :class:`DialogContext`
:return: The dialog turn result
:rtype: :class:`DialogTurnResult`
.. remarks::
Called when a prompt dialog is the active dialog and the user replied with a new activity.
If the task is successful, the result indicates whether the dialog is still active after
the turn has been processed by the dialog.
The prompt generally continues to receive the user's replies until it accepts the
user's reply as valid input for the prompt.
"""
if not dialog_context:
raise TypeError("Prompt(): dc cannot be None.")
# Don't do anything for non-message activities
if dialog_context.context.activity.type != ActivityTypes.message:
return Dialog.end_of_turn
# Perform base recognition
instance = dialog_context.active_dialog
state = instance.state[self.persisted_state]
options = instance.state[self.persisted_options]
recognized = await self.on_recognize(dialog_context.context, state, options)
# Validate the return value
is_valid = False
if self._validator is not None:
prompt_context = PromptValidatorContext(
dialog_context.context, recognized, state, options
)
is_valid = await self._validator(prompt_context)
if options is None:
options = PromptOptions()
options.number_of_attempts += 1
else:
if recognized.succeeded:
is_valid = True
# Return recognized value or re-prompt
if is_valid:
return await dialog_context.end_dialog(recognized.value)
if not dialog_context.context.responded:
await self.on_prompt(dialog_context.context, state, options, True)
return Dialog.end_of_turn
async def resume_dialog(
self, dialog_context: DialogContext, reason: DialogReason, result: object
) -> DialogTurnResult:
"""
Resumes a dialog.
:param dialog_context: The dialog context for the current turn of the conversation.
:type dialog_context: :class:`DialogContext`
:param reason: An enum indicating why the dialog resumed.
:type reason: :class:`DialogReason`
:param result: Optional, value returned from the previous dialog on the stack.
:type result: object
:return: The dialog turn result
:rtype: :class:`DialogTurnResult`
.. remarks::
Called when a prompt dialog resumes being the active dialog on the dialog stack,
such as when the previous active dialog on the stack completes.
If the task is successful, the result indicates whether the dialog is still
active after the turn has been processed by the dialog.
Prompts are typically leaf nodes on the stack but the dev is free to push other dialogs
on top of the stack which will result in the prompt receiving an unexpected call to
:meth:resume_dialog() when the pushed on dialog ends.
Simply re-prompt the user to avoid that the prompt ends prematurely.
"""
await self.reprompt_dialog(dialog_context.context, dialog_context.active_dialog)
return Dialog.end_of_turn
async def reprompt_dialog(self, context: TurnContext, instance: DialogInstance):
"""
Reprompts user for input.
:param context: Context for the current turn of conversation with the user
:type context: :class:`botbuilder.core.TurnContext`
:param instance: The instance of the dialog on the stack
:type instance: :class:`DialogInstance`
:return: A task representing the asynchronous operation
"""
state = instance.state[self.persisted_state]
options = instance.state[self.persisted_options]
await self.on_prompt(context, state, options, False)
@abstractmethod
async def on_prompt(
self,
turn_context: TurnContext,
state: Dict[str, object],
options: PromptOptions,
is_retry: bool,
):
"""
Prompts user for input. When overridden in a derived class, prompts the user for input.
:param turn_context: Context for the current turn of conversation with the user
:type turn_context: :class:`botbuilder.core.TurnContext`
:param state: Contains state for the current instance of the prompt on the dialog stack
:type state: :class:`Dict`
:param options: A prompt options object constructed from:meth:`DialogContext.prompt()`
:type options: :class:`PromptOptions`
:param is_retry: Determines whether `prompt` or `retry_prompt` should be used
:type is_retry: bool
:return: A task representing the asynchronous operation.
"""
@abstractmethod
async def on_recognize(
self,
turn_context: TurnContext,
state: Dict[str, object],
options: PromptOptions,
):
"""
Recognizes the user's input.
:param turn_context: Context for the current turn of conversation with the user
:type turn_context: :class:`botbuilder.core.TurnContext`
:param state: Contains state for the current instance of the prompt on the dialog stack
:type state: :class:`Dict`
:param options: A prompt options object constructed from :meth:`DialogContext.prompt()`
:type options: :class:`PromptOptions`
:return: A task representing the asynchronous operation.
.. note::
When overridden in a derived class, attempts to recognize the user's input.
"""
def append_choices(
self,
prompt: Activity,
channel_id: str,
choices: List[Choice],
style: ListStyle,
options: ChoiceFactoryOptions = None,
) -> Activity:
"""
Composes an output activity containing a set of choices.
:param prompt: The prompt to append the user's choice to
:type prompt:
:param channel_id: Id of the channel the prompt is being sent to
:type channel_id: str
:param: choices: List of choices to append
:type choices: :class:`List`
:param: style: Configured style for the list of choices
:type style: :class:`ListStyle`
:param: options: Optional formatting options to use when presenting the choices
:type style: :class:`ChoiceFactoryOptions`
:return: A task representing the asynchronous operation
.. remarks::
If the task is successful, the result contains the updated activity.
When overridden in a derived class, appends choices to the activity when the user
is prompted for input. This is an helper function to compose an output activity
containing a set of choices.
"""
# Get base prompt text (if any)
text = prompt.text if prompt is not None and prompt.text else ""
# Create temporary msg
# TODO: fix once ChoiceFactory complete
def inline() -> Activity:
return ChoiceFactory.inline(choices, text, None, options)
def list_style() -> Activity:
return ChoiceFactory.list_style(choices, text, None, options)
def suggested_action() -> Activity:
return ChoiceFactory.suggested_action(choices, text)
def hero_card() -> Activity:
return ChoiceFactory.hero_card(choices, text)
def list_style_none() -> Activity:
activity = Activity(type=ActivityTypes.message)
activity.text = text
return activity
def default() -> Activity:
return ChoiceFactory.for_channel(channel_id, choices, text, None, options)
# Maps to values in ListStyle Enum
switcher = {
0: list_style_none,
1: default,
2: inline,
3: list_style,
4: suggested_action,
5: hero_card,
}
msg = switcher.get(int(style.value), default)()
# Update prompt with text, actions and attachments
if prompt:
# clone the prompt the set in the options (note ActivityEx has Properties so this is the safest mechanism)
prompt = copy.copy(prompt)
prompt.text = msg.text
if (
msg.suggested_actions is not None
and msg.suggested_actions.actions is not None
and msg.suggested_actions.actions
):
prompt.suggested_actions = msg.suggested_actions
if msg.attachments:
if prompt.attachments:
prompt.attachments.extend(msg.attachments)
else:
prompt.attachments = msg.attachments
return prompt
# TODO: Update to InputHints.ExpectingInput;
msg.input_hint = None
return msg
|
botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/prompts/prompt.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/prompts/prompt.py",
"repo_id": "botbuilder-python",
"token_count": 4994
}
| 406 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import os
from setuptools import setup
REQUIRES = [
"regex>=2022.1.18",
"emoji==1.7.0",
"recognizers-text-date-time>=1.0.2a1",
"recognizers-text-number-with-unit>=1.0.2a1",
"recognizers-text-number>=1.0.2a1",
"recognizers-text>=1.0.2a1",
"recognizers-text-choice>=1.0.2a1",
"babel==2.9.1",
"botbuilder-schema==4.16.0",
"botframework-connector==4.16.0",
"botbuilder-core==4.16.0",
]
TEST_REQUIRES = ["aiounittest==1.3.0"]
root = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(root, "botbuilder", "dialogs", "about.py")) as f:
package_info = {}
info = f.read()
exec(info, package_info)
with open(os.path.join(root, "README.rst"), encoding="utf-8") as f:
long_description = f.read()
setup(
name=package_info["__title__"],
version=package_info["__version__"],
url=package_info["__uri__"],
author=package_info["__author__"],
description=package_info["__description__"],
keywords=["BotBuilderDialogs", "bots", "ai", "botframework", "botbuilder"],
long_description=long_description,
long_description_content_type="text/x-rst",
license=package_info["__license__"],
packages=[
"botbuilder.dialogs",
"botbuilder.dialogs.prompts",
"botbuilder.dialogs.choices",
"botbuilder.dialogs.skills",
"botbuilder.dialogs.memory",
"botbuilder.dialogs.memory.path_resolvers",
"botbuilder.dialogs.memory.scopes",
],
install_requires=REQUIRES + TEST_REQUIRES,
tests_require=TEST_REQUIRES,
include_package_data=True,
classifiers=[
"Programming Language :: Python :: 3.7",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Development Status :: 5 - Production/Stable",
"Topic :: Scientific/Engineering :: Artificial Intelligence",
],
)
|
botbuilder-python/libraries/botbuilder-dialogs/setup.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-dialogs/setup.py",
"repo_id": "botbuilder-python",
"token_count": 847
}
| 407 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# pylint: disable=ungrouped-imports
import enum
from typing import List
import uuid
import aiounittest
from botframework.connector.auth import ClaimsIdentity, AuthenticationConstants
from botbuilder.core import (
TurnContext,
MessageFactory,
MemoryStorage,
ConversationState,
UserState,
AdapterExtensions,
BotAdapter,
)
from botbuilder.core.adapters import (
TestFlow,
TestAdapter,
)
from botbuilder.core.skills import (
SkillHandler,
SkillConversationReference,
)
from botbuilder.core.transcript_logger import (
TranscriptLoggerMiddleware,
ConsoleTranscriptLogger,
)
from botbuilder.schema import ActivityTypes, Activity, EndOfConversationCodes
from botbuilder.dialogs import (
ComponentDialog,
TextPrompt,
WaterfallDialog,
DialogInstance,
DialogReason,
WaterfallStepContext,
PromptOptions,
Dialog,
DialogExtensions,
DialogEvents,
)
class SimpleComponentDialog(ComponentDialog):
def __init__(self):
super().__init__("SimpleComponentDialog")
self.add_dialog(TextPrompt("TextPrompt"))
self.add_dialog(
WaterfallDialog("WaterfallDialog", [self.prompt_for_name, self.final_step])
)
self.initial_dialog_id = "WaterfallDialog"
self.end_reason = DialogReason.BeginCalled
async def end_dialog(
self, context: TurnContext, instance: DialogInstance, reason: DialogReason
) -> None:
self.end_reason = reason
return await super().end_dialog(context, instance, reason)
async def prompt_for_name(self, step_context: WaterfallStepContext):
return await step_context.prompt(
"TextPrompt",
PromptOptions(
prompt=MessageFactory.text("Hello, what is your name?"),
retry_prompt=MessageFactory.text("Hello, what is your name again?"),
),
)
async def final_step(self, step_context: WaterfallStepContext):
await step_context.context.send_activity(
f"Hello {step_context.result}, nice to meet you!"
)
return await step_context.end_dialog(step_context.result)
class FlowTestCase(enum.Enum):
root_bot_only = 1
root_bot_consuming_skill = 2
middle_skill = 3
leaf_skill = 4
class DialogExtensionsTests(aiounittest.AsyncTestCase):
def __init__(self, methodName):
super().__init__(methodName)
self.eoc_sent: Activity = None
self.skill_bot_id = str(uuid.uuid4())
self.parent_bot_id = str(uuid.uuid4())
async def handles_bot_and_skills_test_cases(
self, test_case: FlowTestCase, send_eoc: bool
):
dialog = SimpleComponentDialog()
test_flow = self.create_test_flow(dialog, test_case)
await test_flow.send("Hi")
await test_flow.assert_reply("Hello, what is your name?")
await test_flow.send("SomeName")
await test_flow.assert_reply("Hello SomeName, nice to meet you!")
assert dialog.end_reason == DialogReason.EndCalled
if send_eoc:
self.assertIsNotNone(
self.eoc_sent, "Skills should send EndConversation to channel"
)
assert ActivityTypes.end_of_conversation == self.eoc_sent.type
assert EndOfConversationCodes.completed_successfully == self.eoc_sent.code
assert self.eoc_sent.value == "SomeName"
else:
self.assertIsNone(
self.eoc_sent, "Root bot should not send EndConversation to channel"
)
async def test_handles_root_bot_only(self):
return await self.handles_bot_and_skills_test_cases(
FlowTestCase.root_bot_only, False
)
async def test_handles_root_bot_consuming_skill(self):
return await self.handles_bot_and_skills_test_cases(
FlowTestCase.root_bot_consuming_skill, False
)
async def test_handles_middle_skill(self):
return await self.handles_bot_and_skills_test_cases(
FlowTestCase.middle_skill, True
)
async def test_handles_leaf_skill(self):
return await self.handles_bot_and_skills_test_cases(
FlowTestCase.leaf_skill, True
)
async def test_skill_handles_eoc_from_parent(self):
dialog = SimpleComponentDialog()
test_flow = self.create_test_flow(dialog, FlowTestCase.leaf_skill)
await test_flow.send("Hi")
await test_flow.assert_reply("Hello, what is your name?")
await test_flow.send(
Activity(
type=ActivityTypes.end_of_conversation,
caller_id=self.parent_bot_id,
)
)
self.assertIsNone(
self.eoc_sent,
"Skill should not send back EoC when an EoC is sent from a parent",
)
assert dialog.end_reason == DialogReason.CancelCalled
async def test_skill_handles_reprompt_from_parent(self):
dialog = SimpleComponentDialog()
test_flow = self.create_test_flow(dialog, FlowTestCase.leaf_skill)
await test_flow.send("Hi")
await test_flow.assert_reply("Hello, what is your name?")
await test_flow.send(
Activity(
type=ActivityTypes.event,
caller_id=self.parent_bot_id,
name=DialogEvents.reprompt_dialog,
)
)
await test_flow.assert_reply("Hello, what is your name?")
assert dialog.end_reason == DialogReason.BeginCalled
def create_test_flow(self, dialog: Dialog, test_case: FlowTestCase) -> TestFlow:
conversation_id = str(uuid.uuid4())
storage = MemoryStorage()
convo_state = ConversationState(storage)
user_state = UserState(storage)
async def logic(context: TurnContext):
if test_case != FlowTestCase.root_bot_only:
claims_identity = ClaimsIdentity(
{
AuthenticationConstants.VERSION_CLAIM: "2.0",
AuthenticationConstants.AUDIENCE_CLAIM: self.skill_bot_id,
AuthenticationConstants.AUTHORIZED_PARTY: self.parent_bot_id,
},
True,
)
context.turn_state[BotAdapter.BOT_IDENTITY_KEY] = claims_identity
if test_case == FlowTestCase.root_bot_consuming_skill:
context.turn_state[
SkillHandler.SKILL_CONVERSATION_REFERENCE_KEY
] = SkillConversationReference(
None, AuthenticationConstants.TO_CHANNEL_FROM_BOT_OAUTH_SCOPE
)
if test_case == FlowTestCase.middle_skill:
context.turn_state[
SkillHandler.SKILL_CONVERSATION_REFERENCE_KEY
] = SkillConversationReference(None, self.parent_bot_id)
async def capture_eoc(
inner_context: TurnContext, activities: List[Activity], next
): # pylint: disable=unused-argument
for activity in activities:
if activity.type == ActivityTypes.end_of_conversation:
self.eoc_sent = activity
break
return await next()
context.on_send_activities(capture_eoc)
await DialogExtensions.run_dialog(
dialog, context, convo_state.create_property("DialogState")
)
adapter = TestAdapter(
logic, TestAdapter.create_conversation_reference(conversation_id)
)
AdapterExtensions.use_storage(adapter, storage)
AdapterExtensions.use_bot_state(adapter, user_state, convo_state)
adapter.use(TranscriptLoggerMiddleware(ConsoleTranscriptLogger()))
return TestFlow(None, adapter)
|
botbuilder-python/libraries/botbuilder-dialogs/tests/test_dialogextensions.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-dialogs/tests/test_dialogextensions.py",
"repo_id": "botbuilder-python",
"token_count": 3555
}
| 408 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from logging import Logger
from typing import Any
from botbuilder.integration.aiohttp import ConfigurationServiceClientCredentialFactory
from botbuilder.schema import Activity
from botframework.connector import HttpClientFactory
from botframework.connector.auth import (
BotFrameworkAuthentication,
ClaimsIdentity,
UserTokenClient,
ConnectorFactory,
AuthenticateRequestResult,
ServiceClientCredentialsFactory,
AuthenticationConfiguration,
BotFrameworkAuthenticationFactory,
)
from botframework.connector.skills import BotFrameworkClient
class ConfigurationBotFrameworkAuthentication(BotFrameworkAuthentication):
def __init__(
self,
configuration: Any,
*,
credentials_factory: ServiceClientCredentialsFactory = None,
auth_configuration: AuthenticationConfiguration = None,
http_client_factory: HttpClientFactory = None,
logger: Logger = None
):
self._inner: BotFrameworkAuthentication = (
BotFrameworkAuthenticationFactory.create(
channel_service=getattr(configuration, "CHANNEL_SERVICE", None),
validate_authority=getattr(configuration, "VALIDATE_AUTHORITY", True),
to_channel_from_bot_login_url=getattr(
configuration, "TO_CHANNEL_FROM_BOT_LOGIN_URL", None
),
to_channel_from_bot_oauth_scope=getattr(
configuration, "TO_CHANNEL_FROM_BOT_OAUTH_SCOPE", None
),
to_bot_from_channel_token_issuer=getattr(
configuration, "TO_BOT_FROM_CHANNEL_TOKEN_ISSUER", None
),
oauth_url=getattr(configuration, "OAUTH_URL", None),
to_bot_from_channel_open_id_metadata_url=getattr(
configuration, "TO_BOT_FROM_CHANNEL_OPENID_METADATA_URL", None
),
to_bot_from_emulator_open_id_metadata_url=getattr(
configuration, "TO_BOT_FROM_EMULATOR_OPENID_METADATA_URL", None
),
caller_id=getattr(configuration, "CALLER_ID", None),
credential_factory=(
credentials_factory
if credentials_factory
else ConfigurationServiceClientCredentialFactory(configuration)
),
auth_configuration=(
auth_configuration
if auth_configuration
else AuthenticationConfiguration()
),
http_client_factory=http_client_factory,
logger=logger,
)
)
async def authenticate_request(
self, activity: Activity, auth_header: str
) -> AuthenticateRequestResult:
return await self._inner.authenticate_request(activity, auth_header)
async def authenticate_streaming_request(
self, auth_header: str, channel_id_header: str
) -> AuthenticateRequestResult:
return await self._inner.authenticate_streaming_request(
auth_header, channel_id_header
)
def create_connector_factory(
self, claims_identity: ClaimsIdentity
) -> ConnectorFactory:
return self._inner.create_connector_factory(claims_identity)
async def create_user_token_client(
self, claims_identity: ClaimsIdentity
) -> UserTokenClient:
return await self._inner.create_user_token_client(claims_identity)
def create_bot_framework_client(self) -> BotFrameworkClient:
return self._inner.create_bot_framework_client()
def get_originating_audience(self) -> str:
return self._inner.get_originating_audience()
async def authenticate_channel_request(self, auth_header: str) -> ClaimsIdentity:
return await self._inner.authenticate_channel_request(auth_header)
|
botbuilder-python/libraries/botbuilder-integration-aiohttp/botbuilder/integration/aiohttp/configuration_bot_framework_authentication.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-integration-aiohttp/botbuilder/integration/aiohttp/configuration_bot_framework_authentication.py",
"repo_id": "botbuilder-python",
"token_count": 1705
}
| 409 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""Telemetry processor for aiohttp."""
import sys
from botbuilder.applicationinsights.processor.telemetry_processor import (
TelemetryProcessor,
)
from .aiohttp_telemetry_middleware import retrieve_aiohttp_body
class AiohttpTelemetryProcessor(TelemetryProcessor):
def can_process(self) -> bool:
return self.detect_aiohttp()
def get_request_body(self) -> str:
if self.detect_aiohttp():
return retrieve_aiohttp_body()
return None
@staticmethod
def detect_aiohttp() -> bool:
"""Detects if running in aiohttp."""
return "aiohttp" in sys.modules
|
botbuilder-python/libraries/botbuilder-integration-applicationinsights-aiohttp/botbuilder/integration/applicationinsights/aiohttp/aiohttp_telemetry_processor.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-integration-applicationinsights-aiohttp/botbuilder/integration/applicationinsights/aiohttp/aiohttp_telemetry_processor.py",
"repo_id": "botbuilder-python",
"token_count": 255
}
| 410 |
[bdist_wheel]
universal=1
|
botbuilder-python/libraries/botbuilder-schema/setup.cfg/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-schema/setup.cfg",
"repo_id": "botbuilder-python",
"token_count": 10
}
| 411 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
from .channels import Channels
from .connector_client import ConnectorClient
from .emulator_api_client import EmulatorApiClient
from .version import VERSION
from .aiohttp_bf_pipeline import AsyncBfPipeline
from .bot_framework_sdk_client_async import BotFrameworkConnectorConfiguration
from .http_client_base import HttpClientBase
from .http_client_factory import HttpClientFactory
from .http_request import HttpRequest
from .http_response_base import HttpResponseBase
__all__ = [
"AsyncBfPipeline",
"Channels",
"ConnectorClient",
"EmulatorApiClient",
"BotFrameworkConnectorConfiguration",
"HttpClientBase",
"HttpClientFactory",
"HttpRequest",
"HttpResponseBase",
]
__version__ = VERSION
|
botbuilder-python/libraries/botframework-connector/botframework/connector/__init__.py/0
|
{
"file_path": "botbuilder-python/libraries/botframework-connector/botframework/connector/__init__.py",
"repo_id": "botbuilder-python",
"token_count": 285
}
| 412 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from logging import Logger
from botbuilder.schema import CallerIdConstants
from ..bot_framework_sdk_client_async import BotFrameworkConnectorConfiguration
from ..http_client_factory import HttpClientFactory
from ._built_in_bot_framework_authentication import _BuiltinBotFrameworkAuthentication
from .authentication_configuration import AuthenticationConfiguration
from .government_constants import GovernmentConstants
from .service_client_credentials_factory import ServiceClientCredentialsFactory
class _GovernmentCloudBotFrameworkAuthentication(_BuiltinBotFrameworkAuthentication):
def __init__(
self,
credentials_factory: ServiceClientCredentialsFactory,
auth_configuration: AuthenticationConfiguration,
http_client_factory: HttpClientFactory,
connector_client_configuration: BotFrameworkConnectorConfiguration = None,
logger: Logger = None,
):
super(_GovernmentCloudBotFrameworkAuthentication, self).__init__(
GovernmentConstants.TO_CHANNEL_FROM_BOT_OAUTH_SCOPE,
GovernmentConstants.TO_CHANNEL_FROM_BOT_LOGIN_URL_PREFIX,
CallerIdConstants.us_gov_channel,
GovernmentConstants.CHANNEL_SERVICE,
GovernmentConstants.OAUTH_URL_GOV,
credentials_factory,
auth_configuration,
http_client_factory,
connector_client_configuration,
logger,
)
|
botbuilder-python/libraries/botframework-connector/botframework/connector/auth/_government_cloud_bot_framework_authentication.py/0
|
{
"file_path": "botbuilder-python/libraries/botframework-connector/botframework/connector/auth/_government_cloud_bot_framework_authentication.py",
"repo_id": "botbuilder-python",
"token_count": 538
}
| 413 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from typing import Union
import jwt
from .jwt_token_extractor import JwtTokenExtractor
from .verify_options import VerifyOptions
from .authentication_constants import AuthenticationConstants
from .credential_provider import CredentialProvider
from .claims_identity import ClaimsIdentity
from .government_constants import GovernmentConstants
from .channel_provider import ChannelProvider
class EmulatorValidation:
APP_ID_CLAIM = "appid"
VERSION_CLAIM = "ver"
TO_BOT_FROM_EMULATOR_TOKEN_VALIDATION_PARAMETERS = VerifyOptions(
issuer=[
# Auth v3.1, 1.0 token
"https://sts.windows.net/d6d49420-f39b-4df7-a1dc-d59a935871db/",
# Auth v3.1, 2.0 token
"https://login.microsoftonline.com/d6d49420-f39b-4df7-a1dc-d59a935871db/v2.0",
# Auth v3.2, 1.0 token
"https://sts.windows.net/f8cdef31-a31e-4b4a-93e4-5f571e91255a/",
# Auth v3.2, 2.0 token
"https://login.microsoftonline.com/f8cdef31-a31e-4b4a-93e4-5f571e91255a/v2.0",
# ???
"https://sts.windows.net/72f988bf-86f1-41af-91ab-2d7cd011db47/",
# Auth for US Gov, 1.0 token
"https://sts.windows.net/cab8a31a-1906-4287-a0d8-4eef66b95f6e/",
# Auth for US Gov, 2.0 token
"https://login.microsoftonline.us/cab8a31a-1906-4287-a0d8-4eef66b95f6e/v2.0",
# Auth for US Gov, 1.0 token
"https://login.microsoftonline.us/f8cdef31-a31e-4b4a-93e4-5f571e91255a/",
# Auth for US Gov, 2.0 token
"https://login.microsoftonline.us/f8cdef31-a31e-4b4a-93e4-5f571e91255a/v2.0",
],
audience=None,
clock_tolerance=5 * 60,
ignore_expiration=False,
)
@staticmethod
def is_token_from_emulator(auth_header: str) -> bool:
"""Determines if a given Auth header is from the Bot Framework Emulator
:param auth_header: Bearer Token, in the 'Bearer [Long String]' Format.
:type auth_header: str
:return: True, if the token was issued by the Emulator. Otherwise, false.
"""
from .jwt_token_validation import ( # pylint: disable=import-outside-toplevel
JwtTokenValidation,
)
if not JwtTokenValidation.is_valid_token_format(auth_header):
return False
bearer_token = auth_header.split(" ")[1]
# Parse the Big Long String into an actual token.
token = jwt.decode(bearer_token, options={"verify_signature": False})
if not token:
return False
# Is there an Issuer?
issuer = token["iss"]
if not issuer:
# No Issuer, means it's not from the Emulator.
return False
# Is the token issues by a source we consider to be the emulator?
issuer_list = (
EmulatorValidation.TO_BOT_FROM_EMULATOR_TOKEN_VALIDATION_PARAMETERS.issuer
)
if issuer_list and not issuer in issuer_list:
# Not a Valid Issuer. This is NOT a Bot Framework Emulator Token.
return False
# The Token is from the Bot Framework Emulator. Success!
return True
@staticmethod
async def authenticate_emulator_token(
auth_header: str,
credentials: CredentialProvider,
channel_service_or_provider: Union[str, ChannelProvider],
channel_id: str,
) -> ClaimsIdentity:
"""Validate the incoming Auth Header
Validate the incoming Auth Header as a token sent from the Bot Framework Service.
A token issued by the Bot Framework emulator will FAIL this check.
:param auth_header: The raw HTTP header in the format: 'Bearer [longString]'
:type auth_header: str
:param credentials: The user defined set of valid credentials, such as the AppId.
:type credentials: CredentialProvider
:return: A valid ClaimsIdentity.
:raises Exception:
"""
# pylint: disable=import-outside-toplevel
from .jwt_token_validation import JwtTokenValidation
if isinstance(channel_service_or_provider, ChannelProvider):
is_gov = channel_service_or_provider.is_government()
else:
is_gov = JwtTokenValidation.is_government(channel_service_or_provider)
open_id_metadata = (
GovernmentConstants.TO_BOT_FROM_EMULATOR_OPENID_METADATA_URL
if is_gov
else AuthenticationConstants.TO_BOT_FROM_EMULATOR_OPENID_METADATA_URL
)
token_extractor = JwtTokenExtractor(
EmulatorValidation.TO_BOT_FROM_EMULATOR_TOKEN_VALIDATION_PARAMETERS,
open_id_metadata,
AuthenticationConstants.ALLOWED_SIGNING_ALGORITHMS,
)
identity = await token_extractor.get_identity_from_auth_header(
auth_header, channel_id
)
if not identity:
# No valid identity. Not Authorized.
raise PermissionError("Unauthorized. No valid identity.")
if not identity.is_authenticated:
# The token is in some way invalid. Not Authorized.
raise PermissionError("Unauthorized. Is not authenticated")
# Now check that the AppID in the claimset matches
# what we're looking for. Note that in a multi-tenant bot, this value
# comes from developer code that may be reaching out to a service, hence the
# Async validation.
version_claim = identity.get_claim_value(EmulatorValidation.VERSION_CLAIM)
if version_claim is None:
raise PermissionError(
'Unauthorized. "ver" claim is required on Emulator Tokens.'
)
app_id = ""
# The Emulator, depending on Version, sends the AppId via either the
# appid claim (Version 1) or the Authorized Party claim (Version 2).
if not version_claim or version_claim == "1.0":
# either no Version or a version of "1.0" means we should look for
# the claim in the "appid" claim.
app_id_claim = identity.get_claim_value(EmulatorValidation.APP_ID_CLAIM)
if not app_id_claim:
# No claim around AppID. Not Authorized.
raise PermissionError(
"Unauthorized. "
'"appid" claim is required on Emulator Token version "1.0".'
)
app_id = app_id_claim
elif version_claim == "2.0":
# Emulator, "2.0" puts the AppId in the "azp" claim.
app_authz_claim = identity.get_claim_value(
AuthenticationConstants.AUTHORIZED_PARTY
)
if not app_authz_claim:
# No claim around AppID. Not Authorized.
raise PermissionError(
"Unauthorized. "
'"azp" claim is required on Emulator Token version "2.0".'
)
app_id = app_authz_claim
else:
# Unknown Version. Not Authorized.
raise PermissionError(
"Unauthorized. Unknown Emulator Token version ", version_claim, "."
)
is_valid_app_id = await credentials.is_valid_appid(app_id)
if not is_valid_app_id:
raise PermissionError(
"Unauthorized. Invalid AppId passed on token: ", app_id
)
return identity
|
botbuilder-python/libraries/botframework-connector/botframework/connector/auth/emulator_validation.py/0
|
{
"file_path": "botbuilder-python/libraries/botframework-connector/botframework/connector/auth/emulator_validation.py",
"repo_id": "botbuilder-python",
"token_count": 3397
}
| 414 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from enum import Enum
class Channels(str, Enum):
"""
Ids of channels supported by the Bot Builder.
"""
console = "console"
"""Console channel."""
cortana = "cortana"
"""Cortana channel."""
direct_line = "directline"
"""Direct Line channel."""
email = "email"
"""Email channel."""
emulator = "emulator"
"""Emulator channel."""
facebook = "facebook"
"""Facebook channel."""
groupme = "groupme"
"""Group Me channel."""
kik = "kik"
"""Kik channel."""
line = "line"
"""Line channel."""
ms_teams = "msteams"
"""MS Teams channel."""
skype = "skype"
"""Skype channel."""
skype_for_business = "skypeforbusiness"
"""Skype for Business channel."""
slack = "slack"
"""Slack channel."""
sms = "sms"
"""SMS (Twilio) channel."""
telegram = "telegram"
"""Telegram channel."""
webchat = "webchat"
"""WebChat channel."""
|
botbuilder-python/libraries/botframework-connector/botframework/connector/channels.py/0
|
{
"file_path": "botbuilder-python/libraries/botframework-connector/botframework/connector/channels.py",
"repo_id": "botbuilder-python",
"token_count": 404
}
| 415 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
from msrest.service_client import SDKClient
from msrest import Configuration, Serializer, Deserializer
from .. import models
from .version import VERSION
from .operations.teams_operations import TeamsOperations
class TeamsConnectorClientConfiguration(Configuration):
"""Configuration for TeamsConnectorClient
Note that all parameters used to create this instance are saved as instance
attributes.
:param credentials: Subscription credentials which uniquely identify
client subscription.
:type credentials: None
:param str base_url: Service URL
"""
def __init__(self, credentials, base_url=None):
if credentials is None:
raise ValueError("Parameter 'credentials' must not be None.")
if not base_url:
base_url = "https://api.botframework.com"
super(TeamsConnectorClientConfiguration, self).__init__(base_url)
self.add_user_agent("botframework-connector/{}".format(VERSION))
self.credentials = credentials
class TeamsConnectorClient(SDKClient):
"""The Bot Connector REST API extension for Microsoft Teams allows your bot to perform extended
operations on to Microsoft Teams channel configured in the
[Bot Framework Developer Portal](https://dev.botframework.com). The Connector service uses
industry-standard REST and JSON over HTTPS. Client libraries for this REST API are available. See below for a list.
Authentication for both the Bot Connector and Bot State REST APIs is accomplished with JWT Bearer tokens, and is
described in detail in the [Connector Authentication](https://docs.botframework.com/en-us/restapi/authentication)
document.
# Client Libraries for the Bot Connector REST API
* [Bot Builder for C#](https://docs.botframework.com/en-us/csharp/builder/sdkreference/)
* [Bot Builder for Node.js](https://docs.botframework.com/en-us/node/builder/overview/)
© 2016 Microsoft
:ivar config: Configuration for client.
:vartype config: TeamsConnectorClientConfiguration
:ivar teams: Teams operations
:vartype teams: botframework.connector.teams.operations.TeamsOperations
:param credentials: Subscription credentials which uniquely identify
client subscription.
:type credentials: None
:param str base_url: Service URL
"""
def __init__(self, credentials, base_url=None):
self.config = TeamsConnectorClientConfiguration(credentials, base_url)
super(TeamsConnectorClient, self).__init__(self.config.credentials, self.config)
client_models = {
k: v for k, v in models.__dict__.items() if isinstance(v, type)
}
self.api_version = "v3"
self._serialize = Serializer(client_models)
self._deserialize = Deserializer(client_models)
self.teams = TeamsOperations(
self._client, self.config, self._serialize, self._deserialize
)
|
botbuilder-python/libraries/botframework-connector/botframework/connector/teams/teams_connector_client.py/0
|
{
"file_path": "botbuilder-python/libraries/botframework-connector/botframework/connector/teams/teams_connector_client.py",
"repo_id": "botbuilder-python",
"token_count": 984
}
| 416 |
interactions:
- request:
body: '{"bot": {"id": "INVALID"}, "members": [{"id": "U19KH8EHJ:T03CWQ0QB"}],
"activity": {"type": "message", "channelId": "slack", "from": {"id": "INVALID"},
"recipient": {"id": "U19KH8EHJ:T03CWQ0QB"}, "textFormat": "markdown", "attachmentLayout":
"list", "text": "Hi there!"}}'
headers:
Accept: [application/json]
Accept-Encoding: ['gzip, deflate']
Connection: [keep-alive]
Content-Length: ['271']
Content-Type: [application/json; charset=utf-8]
User-Agent: [python/3.6.2 (Windows-10-10.0.16299-SP0) requests/2.18.1 msrest/0.4.23
azure-botframework-connector/3.0]
method: POST
uri: https://slack.botframework.com/v3/conversations
response:
body: {string: "{\r\n \"error\": {\r\n \"code\": \"ServiceError\",\r\n \
\ \"message\": \"Invalid userId: INVALID\"\r\n }\r\n}"}
headers:
cache-control: [no-cache]
content-length: ['94']
content-type: [application/json; charset=utf-8]
date: ['Fri, 29 Dec 2017 15:25:45 GMT']
expires: ['-1']
pragma: [no-cache]
request-context: ['appId=cid-v1:6814484e-c0d5-40ea-9dba-74ff29ca4f62']
server: [Microsoft-IIS/10.0]
strict-transport-security: [max-age=31536000]
x-powered-by: [ASP.NET]
status: {code: 400, message: Bad Request}
version: 1
|
botbuilder-python/libraries/botframework-connector/tests/recordings/test_conversations_create_conversation_with_invalid_bot_id_fails.yaml/0
|
{
"file_path": "botbuilder-python/libraries/botframework-connector/tests/recordings/test_conversations_create_conversation_with_invalid_bot_id_fails.yaml",
"repo_id": "botbuilder-python",
"token_count": 633
}
| 417 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from .payload_receiver import PayloadReceiver
from .payload_sender import PayloadSender
from .send_packet import SendPacket
__all__ = ["PayloadReceiver", "PayloadSender", "SendPacket"]
|
botbuilder-python/libraries/botframework-streaming/botframework/streaming/payload_transport/__init__.py/0
|
{
"file_path": "botbuilder-python/libraries/botframework-streaming/botframework/streaming/payload_transport/__init__.py",
"repo_id": "botbuilder-python",
"token_count": 82
}
| 418 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from uuid import UUID
from typing import List
from botframework.streaming.payload_transport import PayloadSender
from botframework.streaming.payloads.models import PayloadTypes, ResponsePayload
from .payload_disassembler import PayloadDisassembler
class ResponseDisassembler(PayloadDisassembler):
def __init__(
self,
sender: PayloadSender,
identifier: UUID,
response: "streaming.StreamingResponse",
):
super().__init__(sender, identifier)
self.response = response
@property
def type(self) -> str:
return PayloadTypes.RESPONSE
async def get_stream(self) -> List[int]:
payload = ResponsePayload(status_code=self.response.status_code)
if self.response.streams:
payload.streams = [
self.get_stream_description(content_stream)
for content_stream in self.response.streams
]
memory_stream: List[int] = []
stream_length: List[int] = []
# TODO: high probability stream length is not necessary
self.serialize(payload, memory_stream, stream_length)
return memory_stream
|
botbuilder-python/libraries/botframework-streaming/botframework/streaming/payloads/disassemblers/response_disassembler.py/0
|
{
"file_path": "botbuilder-python/libraries/botframework-streaming/botframework/streaming/payloads/disassemblers/response_disassembler.py",
"repo_id": "botbuilder-python",
"token_count": 476
}
| 419 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from typing import List
from botframework.streaming.payloads import ContentStream
class ReceiveRequest:
def __init__(
self, *, verb: str = None, path: str = None, streams: List[ContentStream] = None
):
self.verb = verb
self.path = path
self.streams: List[ContentStream] = streams or []
async def read_body_as_str(self) -> str:
try:
content_stream = self.streams[0] if self.streams else None
if not content_stream:
# TODO: maybe raise an error
return ""
# TODO: encoding double check
stream = await content_stream.stream.read_until_end()
return bytes(stream).decode("utf-8-sig")
except Exception as error:
raise error
|
botbuilder-python/libraries/botframework-streaming/botframework/streaming/receive_request.py/0
|
{
"file_path": "botbuilder-python/libraries/botframework-streaming/botframework/streaming/receive_request.py",
"repo_id": "botbuilder-python",
"token_count": 362
}
| 420 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from asyncio import Future, iscoroutinefunction, isfuture
from typing import Callable
from botframework.streaming import (
ProtocolAdapter,
ReceiveResponse,
RequestHandler,
StreamingRequest,
)
from botframework.streaming.payloads import RequestManager
from botframework.streaming.payload_transport import PayloadSender, PayloadReceiver
from botframework.streaming.transport import DisconnectedEventArgs
from .web_socket import WebSocket
from .web_socket_transport import WebSocketTransport
class WebSocketServer:
def __init__(self, socket: WebSocket, request_handler: RequestHandler):
if socket is None:
raise TypeError(
f"'socket: {socket.__class__.__name__}' argument can't be None"
)
if not request_handler:
raise TypeError(
f"'request_handler: {request_handler.__class__.__name__}' argument can't be None"
)
self.disconnected_event_handler: Callable[
[object, DisconnectedEventArgs], None
] = None
self._web_socket_transport = WebSocketTransport(socket)
self._request_handler = request_handler
self._request_manager = RequestManager()
self._sender = PayloadSender()
self._sender.disconnected = self._on_connection_disconnected
self._receiver = PayloadReceiver()
self._receiver.disconnected = self._on_connection_disconnected
self._protocol_adapter = ProtocolAdapter(
self._request_handler, self._request_manager, self._sender, self._receiver
)
self._closed_signal: Future = None
self._is_disconnecting: bool = False
@property
def is_connected(self) -> bool:
return self._sender.is_connected and self._receiver.is_connected
async def start(self):
self._closed_signal = Future()
self._sender.connect(self._web_socket_transport)
await self._receiver.connect(self._web_socket_transport)
return self._closed_signal
async def send(self, request: StreamingRequest) -> ReceiveResponse:
if not request:
raise TypeError(
f"'request: {request.__class__.__name__}' argument can't be None"
)
if not self._sender.is_connected or not self._sender.is_connected:
raise RuntimeError("The server is not connected")
return await self._protocol_adapter.send_request(request)
async def disconnect(self):
await self._sender.disconnect()
await self._receiver.disconnect()
async def _on_connection_disconnected(
self, sender: object, event_args: object # pylint: disable=unused-argument
):
if not self._is_disconnecting:
self._is_disconnecting = True
if self._closed_signal:
self._closed_signal.set_result("close")
self._closed_signal = None
if sender in [self._sender, self._receiver]:
if iscoroutinefunction(sender.disconnect) or isfuture(
sender.disconnect
):
await sender.disconnect()
else:
sender.disconnect()
if self.disconnected_event_handler:
# pylint: disable=not-callable
self.disconnected_event_handler(self, DisconnectedEventArgs.empty)
self._is_disconnecting = False
|
botbuilder-python/libraries/botframework-streaming/botframework/streaming/transport/web_socket/web_socket_server.py/0
|
{
"file_path": "botbuilder-python/libraries/botframework-streaming/botframework/streaming/transport/web_socket/web_socket_server.py",
"repo_id": "botbuilder-python",
"token_count": 1434
}
| 421 |
from typing import List
from botbuilder.core import (
ActivityHandler,
BotFrameworkAdapter,
ConversationState,
UserState,
MessageFactory,
TurnContext,
)
from botbuilder.dialogs import DialogState
from botframework.connector.auth import MicrosoftAppCredentials
from config import DefaultConfig
from helpers.dialog_helper import DialogHelper
from dialogs import MainDialog
class ChildBot(ActivityHandler):
def __init__(
self,
dialog: MainDialog,
user_state: UserState,
conversation_state: ConversationState,
config: DefaultConfig,
):
self._user_state = user_state
self._conversation_state = conversation_state
self._dialog = dialog
self._connection_name = config.CONNECTION_NAME
self._config = config
async def on_turn(self, turn_context: TurnContext):
await super().on_turn(turn_context)
await self._conversation_state.save_changes(turn_context)
await self._user_state.save_changes(turn_context)
async def on_sign_in_invoke( # pylint: disable=unused-argument
self, turn_context: TurnContext
):
await self._conversation_state.load(turn_context, True)
await self._user_state.load(turn_context, True)
await DialogHelper.run_dialog(
self._dialog,
turn_context,
self._conversation_state.create_property(DialogState.__name__)
)
async def on_message_activity(self, turn_context: TurnContext):
if turn_context.activity.channel_id != "emulator":
if "skill login" in turn_context.activity.text:
await self._conversation_state.load(turn_context, True)
await self._user_state.load(turn_context, True)
await DialogHelper.run_dialog(
self._dialog,
turn_context,
self._conversation_state.create_property(DialogState.__name__)
)
return
elif "skill logout" in turn_context.activity.text:
adapter: BotFrameworkAdapter = turn_context.adapter
await adapter.sign_out_user(
turn_context,
self._connection_name,
turn_context.activity.from_property.id,
MicrosoftAppCredentials(self._config.APP_ID, self._config.APP_PASSWORD))
await turn_context.send_activity(MessageFactory.text("logout from child bot successful"))
else:
await turn_context.send_activity(MessageFactory.text("child: activity (1)"))
await turn_context.send_activity(MessageFactory.text("child: activity (2)"))
await turn_context.send_activity(MessageFactory.text("child: activity (3)"))
await turn_context.send_activity(MessageFactory.text(f"child: {turn_context.activity.text}"))
|
botbuilder-python/tests/experimental/sso/child/bots/child_bot.py/0
|
{
"file_path": "botbuilder-python/tests/experimental/sso/child/bots/child_bot.py",
"repo_id": "botbuilder-python",
"token_count": 1234
}
| 422 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from aiohttp import web
from aiohttp.web import Request, Response
from botframework.connector.auth import AuthenticationConfiguration, SimpleCredentialProvider
from botbuilder.core.integration import aiohttp_channel_service_routes, BotFrameworkHttpClient
from botbuilder.schema import Activity
from config import DefaultConfig
from routing_id_factory import RoutingIdFactory
from routing_handler import RoutingHandler
CONFIG = DefaultConfig()
CREDENTIAL_PROVIDER = SimpleCredentialProvider(CONFIG.APP_ID, CONFIG.APP_PASSWORD)
CLIENT = BotFrameworkHttpClient(CREDENTIAL_PROVIDER)
AUTH_CONFIG = AuthenticationConfiguration()
TO_URI = CONFIG.NEXT
SERVICE_URL = CONFIG.SERVICE_URL
FACTORY = RoutingIdFactory()
ROUTING_HANDLER = RoutingHandler(FACTORY, CREDENTIAL_PROVIDER, AUTH_CONFIG)
async def messages(req: Request) -> Response:
# Main bot message handler.
if "application/json" in req.headers["Content-Type"]:
body = await req.json()
else:
return Response(status=415)
inbound_activity: Activity = Activity().deserialize(body)
current_conversation_id = inbound_activity.conversation.id
current_service_url = inbound_activity.service_url
next_conversation_id = FACTORY.create_skill_conversation_id(current_conversation_id, current_service_url)
await CLIENT.post_activity(CONFIG.APP_ID, CONFIG.SKILL_APP_ID, TO_URI, SERVICE_URL, next_conversation_id, inbound_activity)
return Response(status=201)
APP = web.Application()
APP.router.add_post("/api/messages", messages)
APP.router.add_routes(aiohttp_channel_service_routes(ROUTING_HANDLER, "/api/connector"))
if __name__ == "__main__":
try:
web.run_app(APP, host="localhost", port=CONFIG.PORT)
except Exception as error:
raise error
|
botbuilder-python/tests/experimental/test-protocol/app.py/0
|
{
"file_path": "botbuilder-python/tests/experimental/test-protocol/app.py",
"repo_id": "botbuilder-python",
"token_count": 621
}
| 423 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="Aringacute" format="2">
<advance width="1200"/>
<unicode hex="01FA"/>
<outline>
<component base="acutecomb.case" yOffset="240"/>
<component base="Aring"/>
</outline>
<lib>
<dict>
<key>com.schriftgestaltung.Glyphs.ComponentInfo</key>
<array>
<dict>
<key>alignment</key>
<integer>-1</integer>
<key>index</key>
<integer>0</integer>
<key>name</key>
<string>acutecomb.case</string>
</dict>
<dict>
<key>alignment</key>
<integer>-1</integer>
<key>index</key>
<integer>1</integer>
<key>name</key>
<string>Aring</string>
</dict>
</array>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/A_ringacute.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/A_ringacute.glif",
"repo_id": "cascadia-code",
"token_count": 425
}
| 424 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="Hbar" format="2">
<advance width="1200"/>
<unicode hex="0126"/>
<outline>
<contour>
<point x="42" y="1002" type="line"/>
<point x="1158" y="1002" type="line"/>
<point x="1158" y="1192" type="line"/>
<point x="42" y="1192" type="line"/>
</contour>
<component base="H"/>
</outline>
<lib>
<dict>
<key>com.schriftgestaltung.Glyphs.ComponentInfo</key>
<array>
<dict>
<key>alignment</key>
<integer>-1</integer>
<key>index</key>
<integer>0</integer>
<key>name</key>
<string>H</string>
</dict>
</array>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/H_bar.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/H_bar.glif",
"repo_id": "cascadia-code",
"token_count": 372
}
| 425 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="ainTwodotsverticalabove-ar.init" format="2">
<advance width="1200"/>
<outline>
<component base="ain-ar.init"/>
<component base="twodotsverticalabove-ar" xOffset="61" yOffset="353"/>
</outline>
<lib>
<dict>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/ainT_wodotsverticalabove-ar.init.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/ainT_wodotsverticalabove-ar.init.glif",
"repo_id": "cascadia-code",
"token_count": 170
}
| 426 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="backslash_backslash.liga" format="2">
<advance width="1200"/>
<outline>
<component base="backslash" xOffset="118"/>
<component base="backslash" xOffset="1000"/>
</outline>
<lib>
<dict>
<key>com.schriftgestaltung.Glyphs.ComponentInfo</key>
<array>
<dict>
<key>alignment</key>
<integer>-1</integer>
<key>index</key>
<integer>0</integer>
<key>name</key>
<string>backslash</string>
</dict>
<dict>
<key>alignment</key>
<integer>-1</integer>
<key>index</key>
<integer>1</integer>
<key>name</key>
<string>backslash</string>
</dict>
</array>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/backslash_backslash.liga.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/backslash_backslash.liga.glif",
"repo_id": "cascadia-code",
"token_count": 421
}
| 427 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="bottomHalfBlackDiamond" format="2">
<advance width="1200"/>
<unicode hex="2B19"/>
<note>
uni2B19
</note>
<outline>
<contour>
<point x="67" y="710" type="line"/>
<point x="600" y="192" type="line"/>
<point x="1133" y="710" type="line"/>
</contour>
<component base="whiteDiamond" xScale="-1" yScale="-1" xOffset="1200" yOffset="1420"/>
</outline>
<lib>
<dict>
<key>com.schriftgestaltung.Glyphs.ComponentInfo</key>
<array>
<dict>
<key>alignment</key>
<integer>-1</integer>
<key>index</key>
<integer>0</integer>
<key>name</key>
<string>whiteDiamond</string>
</dict>
</array>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/bottomH_alfB_lackD_iamond.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/bottomH_alfB_lackD_iamond.glif",
"repo_id": "cascadia-code",
"token_count": 389
}
| 428 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="bulletoperator" format="2">
<advance width="1200"/>
<unicode hex="2219"/>
<outline>
<component base="bullet"/>
</outline>
<lib>
<dict>
<key>com.schriftgestaltung.Glyphs.ComponentInfo</key>
<array>
<dict>
<key>alignment</key>
<integer>-1</integer>
<key>index</key>
<integer>0</integer>
<key>name</key>
<string>bullet</string>
</dict>
</array>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/bulletoperator.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/bulletoperator.glif",
"repo_id": "cascadia-code",
"token_count": 273
}
| 429 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="dad-ar.init" format="2">
<advance width="1200"/>
<outline>
<component base="sad-ar.init"/>
<component base="dotabove-ar" xOffset="180" yOffset="363"/>
</outline>
<lib>
<dict>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/dad-ar.init.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/dad-ar.init.glif",
"repo_id": "cascadia-code",
"token_count": 161
}
| 430 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="dalDotbelow-ar" format="2">
<advance width="1200"/>
<unicode hex="068A"/>
<outline>
<component base="dal-ar"/>
<component base="dotbelow-ar" xOffset="-30" yOffset="-24"/>
</outline>
<lib>
<dict>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/dalD_otbelow-ar.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/dalD_otbelow-ar.glif",
"repo_id": "cascadia-code",
"token_count": 172
}
| 431 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="dalVinvertedbelow-ar" format="2">
<advance width="1200"/>
<unicode hex="075A"/>
<outline>
<component base="dal-ar"/>
<component base="_vinvertedbelow-ar" xOffset="-30" yOffset="-24"/>
</outline>
<lib>
<dict>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/dalV_invertedbelow-ar.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/dalV_invertedbelow-ar.glif",
"repo_id": "cascadia-code",
"token_count": 174
}
| 432 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="ghain-ar.fina" format="2">
<advance width="1200"/>
<outline>
<component base="ain-ar.fina"/>
<component base="dotabove-ar" xOffset="10" yOffset="273"/>
</outline>
<lib>
<dict>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/ghain-ar.fina.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/ghain-ar.fina.glif",
"repo_id": "cascadia-code",
"token_count": 163
}
| 433 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="greater_greater_greater.liga" format="2">
<advance width="1200"/>
<outline>
<component base="greater" xOffset="2256"/>
<component base="greater" xOffset="134"/>
<component base="greater" xOffset="1200"/>
</outline>
<lib>
<dict>
<key>com.schriftgestaltung.Glyphs.ComponentInfo</key>
<array>
<dict>
<key>alignment</key>
<integer>-1</integer>
<key>index</key>
<integer>0</integer>
<key>name</key>
<string>greater</string>
</dict>
<dict>
<key>alignment</key>
<integer>-1</integer>
<key>index</key>
<integer>1</integer>
<key>name</key>
<string>greater</string>
</dict>
<dict>
<key>alignment</key>
<integer>-1</integer>
<key>index</key>
<integer>2</integer>
<key>name</key>
<string>greater</string>
</dict>
</array>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/greater_greater_greater.liga.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/greater_greater_greater.liga.glif",
"repo_id": "cascadia-code",
"token_count": 562
}
| 434 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="guillemetright" format="2">
<advance width="1200"/>
<unicode hex="00BB"/>
<outline>
<component base="guilsinglright" xOffset="-265"/>
<component base="guilsinglright" xOffset="230"/>
</outline>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/guillemetright.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/guillemetright.glif",
"repo_id": "cascadia-code",
"token_count": 106
}
| 435 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="hahHamzaabove-ar.init" format="2">
<advance width="1200"/>
<outline>
<component base="hah-ar.init"/>
<component base="hamzaabove-ar" xOffset="-54" yOffset="-190"/>
</outline>
<lib>
<dict>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/hahH_amzaabove-ar.init.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/hahH_amzaabove-ar.init.glif",
"repo_id": "cascadia-code",
"token_count": 168
}
| 436 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="hahThreedotsabove-ar.init" format="2">
<advance width="1200"/>
<outline>
<component base="hah-ar.init"/>
<component base="threedotsupabove-ar" xOffset="-34" yOffset="372"/>
</outline>
<lib>
<dict>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/hahT_hreedotsabove-ar.init.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/hahT_hreedotsabove-ar.init.glif",
"repo_id": "cascadia-code",
"token_count": 170
}
| 437 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="highhamzaWaw-ar" format="2">
<advance width="1200"/>
<unicode hex="0676"/>
<anchor x="573" y="1120" name="top"/>
<outline>
<component base="waw-ar" yOffset="3"/>
<component base="highhamza-ar" xOffset="383" yOffset="-337"/>
</outline>
<lib>
<dict>
<key>com.schriftgestaltung.Glyphs.ComponentInfo</key>
<array>
<dict>
<key>alignment</key>
<integer>-1</integer>
<key>index</key>
<integer>0</integer>
<key>name</key>
<string>waw-ar</string>
</dict>
<dict>
<key>anchor</key>
<string>top</string>
<key>index</key>
<integer>1</integer>
<key>name</key>
<string>highhamza-ar</string>
</dict>
</array>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/highhamzaW_aw-ar.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/highhamzaW_aw-ar.glif",
"repo_id": "cascadia-code",
"token_count": 499
}
| 438 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="jeemTwodotsabove-ar" format="2">
<advance width="1200"/>
<unicode hex="08A2"/>
<outline>
<component base="jeem-ar"/>
<component base="twodotshorizontalabove-ar" xOffset="-34" yOffset="392"/>
</outline>
<lib>
<dict>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/jeemT_wodotsabove-ar.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/jeemT_wodotsabove-ar.glif",
"repo_id": "cascadia-code",
"token_count": 179
}
| 439 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="kehehThreedotsupbelow-ar.init" format="2">
<advance width="1200"/>
<outline>
<component base="keheh-ar.init"/>
<component base="threedotsupbelow-ar" xOffset="-33" yOffset="-24"/>
</outline>
<lib>
<dict>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/kehehT_hreedotsupbelow-ar.init.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/kehehT_hreedotsupbelow-ar.init.glif",
"repo_id": "cascadia-code",
"token_count": 174
}
| 440 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.