<commit_before>package dnsimple

import (
	"fmt"
)

// DomainsService handles communication with the domain related
// methods of the DNSimple API.
//
// See https://developer.dnsimple.com/v2/domains/
type DomainsService struct {
	client *Client
}

// Domain represents a domain in DNSimple.
type Domain struct {
	ID           int    `json:"id,omitempty"`
	AccountID    int    `json:"account_id,omitempty"`
	RegistrantID int    `json:"registrant_id,omitempty"`
	Name         string `json:"name,omitempty"`
	UnicodeName  string `json:"unicode_name,omitempty"`
	Token        string `json:"token,omitempty"`
	State        string `json:"state,omitempty"`
	AutoRenew    bool   `json:"auto_renew,omitempty"`
	PrivateWhois bool   `json:"private_whois,omitempty"`
	ExpiresOn    string `json:"expires_on,omitempty"`
	CreatedAt    string `json:"created_at,omitempty"`
	UpdatedAt    string `json:"updated_at,omitempty"`
}

// DomainListOptions specifies the optional parameters you can provide
// to customize the DomainsService.ListDomains method.
type DomainListOptions struct {
	// Select domains where the name contains given string.
	NameLike string `url:"name_like,omitempty"`

	// Select domains where the registrant matches given ID.
	RegistrantID int `url:"registrant_id,omitempty"`

	ListOptions
}

// DomainResponse represents a response from an API method that returns a Domain struct.
type DomainResponse struct {
	Response
	Data *Domain `json:"data"`
}

// DomainsResponse represents a response from an API method that returns a collection of Domain struct.
type DomainsResponse struct {
	Response
	Data []Domain `json:"data"`
}

// domainRequest represents a generic wrapper for a domain request,
// when domainWrapper cannot be used because of type constraint on Domain.
type domainRequest struct {
	Domain interface{} `json:"domain"`
}

func domainPath(accountID string, domainIdentifier string) (path string) {
	path = fmt.Sprintf("/%v/domains", accountID)
	if domainIdentifier != "" {
		path += fmt.Sprintf("/%v", domainIdentifier)
	}
	return
}

// ListDomains lists the domains for an account.
//
// See https://developer.dnsimple.com/v2/domains/#list
func (s *DomainsService) ListDomains(accountID string, options *DomainListOptions) (*DomainsResponse, error) {
	path := versioned(domainPath(accountID, ""))
	domainsResponse := &DomainsResponse{}

	path, err := addURLQueryOptions(path, options)
	if err != nil {
		return nil, err
	}

	resp, err := s.client.get(path, domainsResponse)
	if err != nil {
		return nil, err
	}

	domainsResponse.HttpResponse = resp
	return domainsResponse, nil
}

// CreateDomain creates a new domain in the account.
//
// See https://developer.dnsimple.com/v2/domains/#create
func (s *DomainsService) CreateDomain(accountID string, domainAttributes Domain) (*DomainResponse, error) {
	path := versioned(domainPath(accountID, ""))
	domainResponse := &DomainResponse{}

	resp, err := s.client.post(path, domainAttributes, domainResponse)
	if err != nil {
		return nil, err
	}

	domainResponse.HttpResponse = resp
	return domainResponse, nil
}

// GetDomain fetches a domain.
//
// See https://developer.dnsimple.com/v2/domains/#get
func (s *DomainsService) GetDomain(accountID string, domainIdentifier string) (*DomainResponse, error) {
	path := versioned(domainPath(accountID, domainIdentifier))
	domainResponse := &DomainResponse{}

	resp, err := s.client.get(path, domainResponse)
	if err != nil {
		return nil, err
	}

	domainResponse.HttpResponse = resp
	return domainResponse, nil
}

// DeleteDomain PERMANENTLY deletes a domain from the account.
//
// See https://developer.dnsimple.com/v2/domains/#delete
func (s *DomainsService) DeleteDomain(accountID string, domainIdentifier string) (*DomainResponse, error) {
	path := versioned(domainPath(accountID, domainIdentifier))
	domainResponse := &DomainResponse{}

	resp, err := s.client.delete(path, nil, nil)
	if err != nil {
		return nil, err
	}

	domainResponse.HttpResponse = resp
	return domainResponse, nil
}

// ResetDomainToken resets the domain token.
//
// See https://developer.dnsimple.com/v2/domains/#reset-token
func (s *DomainsService) ResetDomainToken(accountID string, domainIdentifier string) (*DomainResponse, error) {
	path := versioned(domainPath(accountID, domainIdentifier) + "/token")
	domainResponse := &DomainResponse{}

	resp, err := s.client.post(path, nil, domainResponse)
	if err != nil {
		return nil, err
	}

	domainResponse.HttpResponse = resp
	return domainResponse, nil
}
<commit_msg>Remove unused method<commit_after>package dnsimple

import (
	"fmt"
)

// DomainsService handles communication with the domain related
// methods of the DNSimple API.
//
// See https://developer.dnsimple.com/v2/domains/
type DomainsService struct {
	client *Client
}

// Domain represents a domain in DNSimple.
type Domain struct {
	ID           int    `json:"id,omitempty"`
	AccountID    int    `json:"account_id,omitempty"`
	RegistrantID int    `json:"registrant_id,omitempty"`
	Name         string `json:"name,omitempty"`
	UnicodeName  string `json:"unicode_name,omitempty"`
	Token        string `json:"token,omitempty"`
	State        string `json:"state,omitempty"`
	AutoRenew    bool   `json:"auto_renew,omitempty"`
	PrivateWhois bool   `json:"private_whois,omitempty"`
	ExpiresOn    string `json:"expires_on,omitempty"`
	CreatedAt    string `json:"created_at,omitempty"`
	UpdatedAt    string `json:"updated_at,omitempty"`
}

// DomainListOptions specifies the optional parameters you can provide
// to customize the DomainsService.ListDomains method.
type DomainListOptions struct {
	// Select domains where the name contains given string.
	NameLike string `url:"name_like,omitempty"`

	// Select domains where the registrant matches given ID.
	RegistrantID int `url:"registrant_id,omitempty"`

	ListOptions
}

// DomainResponse represents a response from an API method that returns a Domain struct.
type DomainResponse struct {
	Response
	Data *Domain `json:"data"`
}

// DomainsResponse represents a response from an API method that returns a collection of Domain struct.
type DomainsResponse struct {
	Response
	Data []Domain `json:"data"`
}

func domainPath(accountID string, domainIdentifier string) (path string) {
	path = fmt.Sprintf("/%v/domains", accountID)
	if domainIdentifier != "" {
		path += fmt.Sprintf("/%v", domainIdentifier)
	}
	return
}

// ListDomains lists the domains for an account.
//
// See https://developer.dnsimple.com/v2/domains/#list
func (s *DomainsService) ListDomains(accountID string, options *DomainListOptions) (*DomainsResponse, error) {
	path := versioned(domainPath(accountID, ""))
	domainsResponse := &DomainsResponse{}

	path, err := addURLQueryOptions(path, options)
	if err != nil {
		return nil, err
	}

	resp, err := s.client.get(path, domainsResponse)
	if err != nil {
		return nil, err
	}

	domainsResponse.HttpResponse = resp
	return domainsResponse, nil
}

// CreateDomain creates a new domain in the account.
//
// See https://developer.dnsimple.com/v2/domains/#create
func (s *DomainsService) CreateDomain(accountID string, domainAttributes Domain) (*DomainResponse, error) {
	path := versioned(domainPath(accountID, ""))
	domainResponse := &DomainResponse{}

	resp, err := s.client.post(path, domainAttributes, domainResponse)
	if err != nil {
		return nil, err
	}

	domainResponse.HttpResponse = resp
	return domainResponse, nil
}

// GetDomain fetches a domain.
//
// See https://developer.dnsimple.com/v2/domains/#get
func (s *DomainsService) GetDomain(accountID string, domainIdentifier string) (*DomainResponse, error) {
	path := versioned(domainPath(accountID, domainIdentifier))
	domainResponse := &DomainResponse{}

	resp, err := s.client.get(path, domainResponse)
	if err != nil {
		return nil, err
	}

	domainResponse.HttpResponse = resp
	return domainResponse, nil
}

// DeleteDomain PERMANENTLY deletes a domain from the account.
//
// See https://developer.dnsimple.com/v2/domains/#delete
func (s *DomainsService) DeleteDomain(accountID string, domainIdentifier string) (*DomainResponse, error) {
	path := versioned(domainPath(accountID, domainIdentifier))
	domainResponse := &DomainResponse{}

	resp, err := s.client.delete(path, nil, nil)
	if err != nil {
		return nil, err
	}

	domainResponse.HttpResponse = resp
	return domainResponse, nil
}

// ResetDomainToken resets the domain token.
//
// See https://developer.dnsimple.com/v2/domains/#reset-token
func (s *DomainsService) ResetDomainToken(accountID string, domainIdentifier string) (*DomainResponse, error) {
	path := versioned(domainPath(accountID, domainIdentifier) + "/token")
	domainResponse := &DomainResponse{}

	resp, err := s.client.post(path, nil, domainResponse)
	if err != nil {
		return nil, err
	}

	domainResponse.HttpResponse = resp
	return domainResponse, nil
}
<|endoftext|>


<commit_before>package scipipe

import (
	"time"
)

type AuditInfo struct {
	Command    string
	Params     map[string]string
	ExecTimeMS time.Duration
	Upstream   map[string]*AuditInfo
}

func NewAuditInfo() *AuditInfo {
	return &AuditInfo{
		Command:    "",
		ExecTimeMS: 0,
		Params:     make(map[string]string),
		Upstream:   make(map[string]*AuditInfo),
	}
}
<commit_msg>Initialize AuditInfo with -1 as ExecTimeMS<commit_after>package scipipe

import (
	"time"
)

type AuditInfo struct {
	Command    string
	Params     map[string]string
	ExecTimeMS time.Duration
	Upstream   map[string]*AuditInfo
}

func NewAuditInfo() *AuditInfo {
	return &AuditInfo{
		Command:    "",
		ExecTimeMS: -1,
		Params:     make(map[string]string),
		Upstream:   make(map[string]*AuditInfo),
	}
}
<|endoftext|>


<commit_before>package makeupdater

// Note this package is exclusively compatible with Drupal 7 make files.

import (
	"errors"
	"fmt"
	"io/ioutil"
	"os"
	"os/exec"
	"strconv"
	"strings"
	"sync"
)

// replaceTextInFile will replace a string of test in a file.
func replaceTextInFile(fullPath string, oldString string, newString string) {
	read, err := ioutil.ReadFile(fullPath)
	if err != nil {
		panic(err)
	}
	newContents := strings.Replace(string(read), oldString, newString, -1)
	err = ioutil.WriteFile(fullPath, []byte(newContents), 0)
	if err != nil {
		panic(err)
	}
}

// removeChar will remove particular characters from a string.
func removeChar(input string, chars ...string) string {
	for _, value := range chars {
		input = strings.Replace(input, value, "", -1)
	}
	return input
}

// inArray will return the quanity of specific input values in the input slice.
func inArray(input []string, subject string) int {
	counter := 0
	for _, value := range input {
		if value == subject {
			counter++
		}
	}
	return counter
}

// GetCoreFromMake will return the major core version used in the input make file.
func GetCoreFromMake(fullpath string) (int64, error) {
	command := fmt.Sprintf("cat %v | grep core", fullpath)
	catCmd := exec.Command("sh", "-c", command)
	cmdOut, cmdErr := catCmd.CombinedOutput()
	if cmdErr != nil {
		fmt.Errorf("Could not execute '%v'", command)
	}
	var majorVersion int64
	for _, line := range strings.Split(string(cmdOut), "\n") {
		line = strings.Replace(line, "core", "", -1)
		line = strings.Replace(line, "=", "", -1)
		line = strings.Replace(line, "\"", "", -1)
		line = strings.Replace(line, ".x", "", -1)
		line = strings.Replace(line, " ", "", -1)
		x, y := strconv.ParseInt(line, 0, 0)
		if y == nil {
			majorVersion = x
		}
	}
	if majorVersion != 0 {
		return majorVersion, nil
	} else {
		return majorVersion, errors.New("Could not identify a version associated to this make file.")
	}
}

// UpdateMake will update the version numbers in a specified make file
func UpdateMake(fullpath string) {
	_, err := os.Stat(fullpath)
	if err != nil {
		panic(err)
	}
	projects := GetProjectsFromMake(fullpath)
	count := 0
	wg := sync.WaitGroup{}
	for _, project := range projects {
		func(project string) {
			majorVersion, _ := GetCoreFromMake(fullpath)
			majorVersionString := fmt.Sprintf("%v", majorVersion)
			if project != "" {
				wg.Add(1)
				catCmd := "cat " + fullpath + " | grep \"projects\\[" + project + "\\]\" | grep version | cut -d '=' -f2"
				z, _ := exec.Command("sh", "-c", catCmd).Output()
				for _, stream := range strings.Split(string(z), "\n") {
					if !strings.Contains(stream, "x-dev") {
					stream = strings.Replace(stream, "\"", "", -1)
					stream = strings.Replace(stream, " ", "", -1)
					if stream != "" {
						command := "drush pm-releases --default-major=" + majorVersionString + " --pipe " + project + " | grep .x- | grep Recommended | cut -d',' -f2"
						x, _ := exec.Command("sh", "-c", command).CombinedOutput()
						for _, Line := range strings.Split(string(x), "\n") {
							if strings.Contains(Line, ".x-") {
								versionNew := removeChar(string(x), " ", "5.x-", "6.x-", "7.x-", "8.x-", "\"", "\n", "\t", "[", "]")
								if len(versionNew) < 15 {
									if fmt.Sprintf("%v", versionNew) != "" && stream != versionNew {
										fmt.Printf("Replacing %v v%v with v%v\n", project, stream, versionNew)
										replaceTextInFile(fullpath, fmt.Sprintf("projects[%v][version] = \"%v\"\n", project, stream), fmt.Sprintf("projects[%v][version] = \"%v\"\n", project, versionNew))
										count++
									}
								} else {
									fmt.Printf("There was an error in checking version numbers for %v, please check it manually.\n", project)
								}
							}
						}
					}
				} else {
						fmt.Printf("Project %v is using development version, do not use in production!\n", project)
					}
				}

			}
			wg.Done()
		}(project)
	}
	wg.Wait()
	if count == 0 {
		fmt.Printf("%v is already up to date.\n", fullpath)
	} else {
		fmt.Printf("Updated %v projects in %v.\n", count, fullpath)
	}
}

// FindDuplicatesInMake will find and report Duplicate projects in Drupal make files.
// It will not return a value.
func FindDuplicatesInMake(makefile string) {
	projects := GetProjectsFromMake(makefile)
	// Run a short report containing information on all duplicates.
	for _, project := range projects {
		projectCounter := 0
		if project != "" {
			catCmd := "cat " + makefile + " | grep \"projects\\[" + project + "\\]\" | grep version | cut -d '=' -f2"
			z, _ := exec.Command("sh", "-c", catCmd).Output()
			for _, stream := range strings.Split(string(z), "\n") {
				if stream != "" {
					projectCounter++
				}
			}
			if projectCounter > 1 {
				fmt.Printf("Found %v instances of project %v\n", projectCounter, project)
			}
		}
	}
}

// GetProjectsFromMake returns a list of projects from a given make file
func GetProjectsFromMake(fullpath string) []string {
	Projects := []string{}
	catCmd := "cat " + fullpath + " | grep projects | cut -d'[' -f2 | cut -d']' -f1 | uniq | sort"
	y, _ := exec.Command("sh", "-c", catCmd).Output()
	rawProjects := strings.Split(string(y), "\n")
	for _, project := range rawProjects {
		project = strings.Replace(project, " ", "", -1)
		if project != "" && project != "projects" {
			if inArray(Projects, project) == 0 {
				Projects = append(Projects, project)
			}
		}
	}
	return Projects
}

// GenerateMake takes a []string of projects and writes out a make file
// Modules are added with the latest recommended version.
func GenerateMake(Projects []string, File string) {
	headerLines := []string{}

	majorVersion, _ := GetCoreFromMake(File)
	majorVersionString := fmt.Sprintf("%v", majorVersion)

	headerLines = append(headerLines, "; Generated by make-updater")
	headerLines = append(headerLines, "; Script created by Fubarhouse")
	headerLines = append(headerLines, "; Toolkit available at github.com/fubarhouse/golang-drush/...")
	headerLines = append(headerLines, "core = "+majorVersionString+".x")
	headerLines = append(headerLines, "api = 2")
	headerLines = append(headerLines, "")

	// Rewrite core, if core is in the original Projects list.

	for _, Project := range Projects {
		coreAppended := 0
		if Project == "drupal" {
			if coreAppended == 0 {
				headerLines = append(headerLines, "; core")
				x, _ := exec.Command("sh", "-c", "drush pm-releases --default-major="+majorVersionString+" --pipe drupal | grep Recommended | cut -d',' -f2").Output()
				ProjectVersion := removeChar(string(x), " ", "5.x-", "6.x-", "7.x-", "8.x-", "\"", "\n", "[", "]")
				headerLines = append(headerLines, "projects[drupal][type] = \"core\"")
				headerLines = append(headerLines, fmt.Sprintf("projects[drupal][version] = \"%v\"", ProjectVersion))
				headerLines = append(headerLines, "projects[drupal][download][type] = \"get\"")
				headerLines = append(headerLines, fmt.Sprintf("projects[drupal][download][url] = \"https://ftp.drupal.org/files/projects/drupal-%v.tar.gz\"", ProjectVersion))
				headerLines = append(headerLines, "")
				coreAppended++
			}
		}
	}

	// Rewrite contrib
	headerLines = append(headerLines, "; modules")
	headerLines = append(headerLines, "defaults[projects][subdir] = contrib")
	headerLines = append(headerLines, "")

	for _, Project := range Projects {

		if Project != "drupal" {
			x, y := exec.Command("sh", "-c", "drush pm-releases --default-major="+majorVersionString+" --pipe "+Project+" | grep Recommended | cut -d',' -f2").Output()
			if y == nil {
				ProjectVersion := removeChar(string(x), " ", "5.x-", "6.x-", "7.x-", "8.x-", "\"", "\n", "[", "]")
				ProjectType := "contrib"
				if ProjectVersion == "" {
					ProjectType = "custom"
				}
				headerLines = append(headerLines, fmt.Sprintf("projects[%v][version] = \"%v\"", Project, ProjectVersion))
				headerLines = append(headerLines, fmt.Sprintf("projects[%v][type] = \"module\"", Project))
				headerLines = append(headerLines, fmt.Sprintf("projects[%v][subdir] = \"%v\"", Project, ProjectType))
				headerLines = append(headerLines, fmt.Sprint(""))
			}
		}
	}

	// Print to path File

	newFile, _ := os.Create(File)
	for _, line := range headerLines {
		fmt.Fprintln(newFile, line)
	}
	newFile.Sync()
	defer newFile.Close()

}
<commit_msg>Change a variable reference causing a few problems...<commit_after>package makeupdater

// Note this package is exclusively compatible with Drupal 7 make files.

import (
	"errors"
	"fmt"
	"io/ioutil"
	"os"
	"os/exec"
	"strconv"
	"strings"
	"sync"
)

// replaceTextInFile will replace a string of test in a file.
func replaceTextInFile(fullPath string, oldString string, newString string) {
	read, err := ioutil.ReadFile(fullPath)
	if err != nil {
		panic(err)
	}
	newContents := strings.Replace(string(read), oldString, newString, -1)
	err = ioutil.WriteFile(fullPath, []byte(newContents), 0)
	if err != nil {
		panic(err)
	}
}

// removeChar will remove particular characters from a string.
func removeChar(input string, chars ...string) string {
	for _, value := range chars {
		input = strings.Replace(input, value, "", -1)
	}
	return input
}

// inArray will return the quanity of specific input values in the input slice.
func inArray(input []string, subject string) int {
	counter := 0
	for _, value := range input {
		if value == subject {
			counter++
		}
	}
	return counter
}

// GetCoreFromMake will return the major core version used in the input make file.
func GetCoreFromMake(fullpath string) (int64, error) {
	command := fmt.Sprintf("cat %v | grep core", fullpath)
	catCmd := exec.Command("sh", "-c", command)
	cmdOut, cmdErr := catCmd.CombinedOutput()
	if cmdErr != nil {
		fmt.Errorf("Could not execute '%v'", command)
	}
	var majorVersion int64
	for _, line := range strings.Split(string(cmdOut), "\n") {
		line = strings.Replace(line, "core", "", -1)
		line = strings.Replace(line, "=", "", -1)
		line = strings.Replace(line, "\"", "", -1)
		line = strings.Replace(line, ".x", "", -1)
		line = strings.Replace(line, " ", "", -1)
		x, y := strconv.ParseInt(line, 0, 0)
		if y == nil {
			majorVersion = x
		}
	}
	if majorVersion != 0 {
		return majorVersion, nil
	} else {
		return majorVersion, errors.New("Could not identify a version associated to this make file.")
	}
}

// UpdateMake will update the version numbers in a specified make file
func UpdateMake(fullpath string) {
	_, err := os.Stat(fullpath)
	if err != nil {
		panic(err)
	}
	projects := GetProjectsFromMake(fullpath)
	count := 0
	wg := sync.WaitGroup{}
	for _, project := range projects {
		func(project string) {
			majorVersion, _ := GetCoreFromMake(fullpath)
			majorVersionString := fmt.Sprintf("%v", majorVersion)
			if project != "" {
				wg.Add(1)
				catCmd := "cat " + fullpath + " | grep \"projects\\[" + project + "\\]\" | grep version | cut -d '=' -f2"
				z, _ := exec.Command("sh", "-c", catCmd).Output()
				for _, stream := range strings.Split(string(z), "\n") {
					if !strings.Contains(stream, "x-dev") {
						stream = strings.Replace(stream, "\"", "", -1)
						stream = strings.Replace(stream, " ", "", -1)
						if stream != "" {
							command := "drush pm-releases --default-major=" + majorVersionString + " --pipe " + project + " | grep .x- | grep Recommended | cut -d',' -f2"
							x, _ := exec.Command("sh", "-c", command).CombinedOutput()
							for _, Line := range strings.Split(string(x), "\n") {
								if strings.Contains(Line, ".x-") {
									versionNew := removeChar(Line, " ", "5.x-", "6.x-", "7.x-", "8.x-", "\"", "\n", "\t", "[", "]")
									if len(versionNew) < 15 {
										if fmt.Sprintf("%v", versionNew) != "" && stream != versionNew {
											fmt.Printf("Replacing %v v%v with v%v\n", project, stream, versionNew)
											replaceTextInFile(fullpath, fmt.Sprintf("projects[%v][version] = \"%v\"\n", project, stream), fmt.Sprintf("projects[%v][version] = \"%v\"\n", project, versionNew))
											count++
										}
									} else {
										fmt.Printf("There was an error in checking version numbers for %v, please check it manually.\n", project)
									}
								}
							}
						}
					} else {
						fmt.Printf("Project %v is using development version, do not use in production!\n", project)
					}
				}

			}
			wg.Done()
		}(project)
	}
	wg.Wait()
	if count == 0 {
		fmt.Printf("%v is already up to date.\n", fullpath)
	} else {
		fmt.Printf("Updated %v projects in %v.\n", count, fullpath)
	}
}

// FindDuplicatesInMake will find and report Duplicate projects in Drupal make files.
// It will not return a value.
func FindDuplicatesInMake(makefile string) {
	projects := GetProjectsFromMake(makefile)
	// Run a short report containing information on all duplicates.
	for _, project := range projects {
		projectCounter := 0
		if project != "" {
			catCmd := "cat " + makefile + " | grep \"projects\\[" + project + "\\]\" | grep version | cut -d '=' -f2"
			z, _ := exec.Command("sh", "-c", catCmd).Output()
			for _, stream := range strings.Split(string(z), "\n") {
				if stream != "" {
					projectCounter++
				}
			}
			if projectCounter > 1 {
				fmt.Printf("Found %v instances of project %v\n", projectCounter, project)
			}
		}
	}
}

// GetProjectsFromMake returns a list of projects from a given make file
func GetProjectsFromMake(fullpath string) []string {
	Projects := []string{}
	catCmd := "cat " + fullpath + " | grep projects | cut -d'[' -f2 | cut -d']' -f1 | uniq | sort"
	y, _ := exec.Command("sh", "-c", catCmd).Output()
	rawProjects := strings.Split(string(y), "\n")
	for _, project := range rawProjects {
		project = strings.Replace(project, " ", "", -1)
		if project != "" && project != "projects" {
			if inArray(Projects, project) == 0 {
				Projects = append(Projects, project)
			}
		}
	}
	return Projects
}

// GenerateMake takes a []string of projects and writes out a make file
// Modules are added with the latest recommended version.
func GenerateMake(Projects []string, File string) {
	headerLines := []string{}

	majorVersion, _ := GetCoreFromMake(File)
	majorVersionString := fmt.Sprintf("%v", majorVersion)

	headerLines = append(headerLines, "; Generated by make-updater")
	headerLines = append(headerLines, "; Script created by Fubarhouse")
	headerLines = append(headerLines, "; Toolkit available at github.com/fubarhouse/golang-drush/...")
	headerLines = append(headerLines, "core = "+majorVersionString+".x")
	headerLines = append(headerLines, "api = 2")
	headerLines = append(headerLines, "")

	// Rewrite core, if core is in the original Projects list.

	for _, Project := range Projects {
		coreAppended := 0
		if Project == "drupal" {
			if coreAppended == 0 {
				headerLines = append(headerLines, "; core")
				x, _ := exec.Command("sh", "-c", "drush pm-releases --default-major="+majorVersionString+" --pipe drupal | grep Recommended | cut -d',' -f2").Output()
				ProjectVersion := removeChar(string(x), " ", "5.x-", "6.x-", "7.x-", "8.x-", "\"", "\n", "[", "]")
				headerLines = append(headerLines, "projects[drupal][type] = \"core\"")
				headerLines = append(headerLines, fmt.Sprintf("projects[drupal][version] = \"%v\"", ProjectVersion))
				headerLines = append(headerLines, "projects[drupal][download][type] = \"get\"")
				headerLines = append(headerLines, fmt.Sprintf("projects[drupal][download][url] = \"https://ftp.drupal.org/files/projects/drupal-%v.tar.gz\"", ProjectVersion))
				headerLines = append(headerLines, "")
				coreAppended++
			}
		}
	}

	// Rewrite contrib
	headerLines = append(headerLines, "; modules")
	headerLines = append(headerLines, "defaults[projects][subdir] = contrib")
	headerLines = append(headerLines, "")

	for _, Project := range Projects {

		if Project != "drupal" {
			x, y := exec.Command("sh", "-c", "drush pm-releases --default-major="+majorVersionString+" --pipe "+Project+" | grep Recommended | cut -d',' -f2").Output()
			if y == nil {
				ProjectVersion := removeChar(string(x), " ", "5.x-", "6.x-", "7.x-", "8.x-", "\"", "\n", "[", "]")
				ProjectType := "contrib"
				if ProjectVersion == "" {
					ProjectType = "custom"
				}
				headerLines = append(headerLines, fmt.Sprintf("projects[%v][version] = \"%v\"", Project, ProjectVersion))
				headerLines = append(headerLines, fmt.Sprintf("projects[%v][type] = \"module\"", Project))
				headerLines = append(headerLines, fmt.Sprintf("projects[%v][subdir] = \"%v\"", Project, ProjectType))
				headerLines = append(headerLines, fmt.Sprint(""))
			}
		}
	}

	// Print to path File

	newFile, _ := os.Create(File)
	for _, line := range headerLines {
		fmt.Fprintln(newFile, line)
	}
	newFile.Sync()
	defer newFile.Close()

}
<|endoftext|>


<commit_before>/*
Copyright 2015 The Kubernetes Authors All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package manager

import (
	"fmt"
	"log"
	"time"
)

// Manager manages a persistent set of Deployments.
type Manager interface {
	ListDeployments() ([]Deployment, error)
	GetDeployment(name string) (*Deployment, error)
	CreateDeployment(t *Template) (*Deployment, error)
	DeleteDeployment(name string, forget bool) (*Deployment, error)
	PutDeployment(name string, t *Template) (*Deployment, error)
	ListManifests(deploymentName string) (map[string]*Manifest, error)
	GetManifest(deploymentName string, manifest string) (*Manifest, error)
	Expand(t *Template) (*Manifest, error)
	ListTypes() []string
	ListInstances(typeName string) []*TypeInstance
}

type manager struct {
	expander   Expander
	deployer   Deployer
	repository Repository
}

// NewManager returns a new initialized Manager.
func NewManager(expander Expander, deployer Deployer, repository Repository) Manager {
	return &manager{expander, deployer, repository}
}

// ListDeployments returns the list of deployments
func (m *manager) ListDeployments() ([]Deployment, error) {
	l, err := m.repository.ListDeployments()
	if err != nil {
		return nil, err
	}
	return l, nil
}

// GetDeployment retrieves the configuration stored for a given deployment
// as well as the current configuration from the cluster.
func (m *manager) GetDeployment(name string) (*Deployment, error) {
	d, err := m.repository.GetDeployment(name)
	if err != nil {
		return nil, err
	}
	latest := getLatestManifest(d.Manifests)
	if latest != nil {
		d.Current = latest.ExpandedConfig
	}
	return d, nil
}

// ListManifests retrieves the manifests for a given deployment
// of each of the deployments in the repository and returns the deployments.
func (m *manager) ListManifests(deploymentName string) (map[string]*Manifest, error) {
	l, err := m.repository.ListManifests(deploymentName)
	if err != nil {
		return nil, err
	}
	return l, nil
}

// GetManifest retrieves the specified manifest for a given deployment
func (m *manager) GetManifest(deploymentName string, manifestName string) (*Manifest, error) {
	d, err := m.repository.GetManifest(deploymentName, manifestName)
	if err != nil {
		return nil, err
	}
	return d, nil
}

// CreateDeployment expands the supplied template, creates the resulting
// configuration in the cluster, creates a new deployment that tracks it,
// and stores the deployment in the repository. Returns the deployment.
func (m *manager) CreateDeployment(t *Template) (*Deployment, error) {
	log.Printf("Creating deployment: %s", t.Name)
	_, err := m.repository.CreateDeployment(t.Name)
	if err != nil {
		log.Printf("CreateDeployment failed %v", err)
		return nil, err
	}

	manifest, err := m.createManifest(t)
	if err != nil {
		log.Printf("Manifest creation failed: %v", err)
		m.repository.SetDeploymentStatus(t.Name, FailedStatus)
		return nil, err
	}

	err = m.repository.AddManifest(t.Name, manifest)
	if err != nil {
		log.Printf("AddManifest failed %v", err)
		m.repository.SetDeploymentStatus(t.Name, FailedStatus)
		return nil, err
	}

	if err := m.deployer.CreateConfiguration(manifest.ExpandedConfig); err != nil {
		// Deployment failed, mark as deleted
		log.Printf("CreateConfiguration failed: %v", err)
		m.repository.SetDeploymentStatus(t.Name, FailedStatus)
		return nil, err
	}

	m.repository.SetDeploymentStatus(t.Name, DeployedStatus)
	// Finally update the type instances for this deployment.
	m.addTypeInstances(t.Name, manifest.Name, manifest.Layout)
	return m.repository.GetValidDeployment(t.Name)
}

func (m *manager) createManifest(t *Template) (*Manifest, error) {
	et, err := m.expander.ExpandTemplate(*t)
	if err != nil {
		log.Printf("Expansion failed %v", err)
		return nil, err
	}

	return &Manifest{
		Name:           generateManifestName(),
		Deployment:     t.Name,
		InputConfig:    t,
		ExpandedConfig: et.Config,
		Layout:         et.Layout,
	}, nil
}

func (m *manager) addTypeInstances(deploymentName string, manifestName string, layout *Layout) {
	m.repository.ClearTypeInstances(deploymentName)

	instances := make(map[string][]*TypeInstance)
	for i, r := range layout.Resources {
		addTypeInstances(&instances, r, deploymentName, manifestName, fmt.Sprintf("$.resources[%d]", i))
	}

	m.repository.SetTypeInstances(deploymentName, instances)
}

func addTypeInstances(instances *map[string][]*TypeInstance, r *LayoutResource, deploymentName string, manifestName string, jsonPath string) {
	// Add this resource.
	inst := &TypeInstance{
		Name:       r.Name,
		Type:       r.Type,
		Deployment: deploymentName,
		Manifest:   manifestName,
		Path:       jsonPath,
	}
	(*instances)[r.Type] = append((*instances)[r.Type], inst)

	// Add all sub resources if they exist.
	for i, sr := range r.Resources {
		addTypeInstances(instances, sr, deploymentName, manifestName, fmt.Sprintf("%s.resources[%d]", jsonPath, i))
	}
}

// DeleteDeployment deletes the configuration for the deployment with
// the supplied identifier from the cluster.repository. If forget is true, then
// the deployment is removed from the repository. Otherwise, it is marked
// as deleted and retained.
func (m *manager) DeleteDeployment(name string, forget bool) (*Deployment, error) {
	log.Printf("Deleting deployment: %s", name)
	d, err := m.repository.GetValidDeployment(name)
	if err != nil {
		return nil, err
	}

	// If there's a latest manifest, delete the underlying resources.
	latest := getLatestManifest(d.Manifests)
	if latest != nil {
		log.Printf("Deleting resources from the latest manifest")
		if err := m.deployer.DeleteConfiguration(latest.ExpandedConfig); err != nil {
			log.Printf("Failed to delete resources from the latest manifest: %v", err)
			return nil, err
		}

		// Create an empty manifest since resources have been deleted.
		err = m.repository.AddManifest(name, &Manifest{Deployment: name, Name: generateManifestName()})
		if err != nil {
			log.Printf("Failed to add empty manifest")
			return nil, err
		}
	}

	d, err = m.repository.DeleteDeployment(name, forget)
	if err != nil {
		return nil, err
	}

	// Finally remove the type instances for this deployment.
	m.repository.ClearTypeInstances(name)

	return d, nil
}

// PutDeployment replaces the configuration of the deployment with
// the supplied identifier in the cluster, and returns the deployment.
func (m *manager) PutDeployment(name string, t *Template) (*Deployment, error) {
	_, err := m.repository.GetValidDeployment(name)
	if err != nil {
		return nil, err
	}

	// TODO(bmelville): This should just return a new manifest filled in.
	et, err := m.expander.ExpandTemplate(*t)
	if err != nil {
		return nil, err
	}

	if err := m.deployer.PutConfiguration(et.Config); err != nil {
		return nil, err
	}

	manifest := &Manifest{
		Deployment:     t.Name,
		Name:           generateManifestName(),
		InputConfig:    t,
		ExpandedConfig: et.Config,
		Layout:         et.Layout,
	}

	err = m.repository.AddManifest(t.Name, manifest)
	if err != nil {
		return nil, err
	}

	// Finally update the type instances for this deployment.
	m.addTypeInstances(t.Name, manifest.Name, manifest.Layout)

	return m.repository.GetValidDeployment(t.Name)
}

func (m *manager) Expand(t *Template) (*Manifest, error) {
	et, err := m.expander.ExpandTemplate(*t)
	if err != nil {
		log.Printf("Expansion failed %v", err)
		return nil, err
	}

	return &Manifest{
		ExpandedConfig: et.Config,
		Layout:         et.Layout,
	}, nil
}

func (m *manager) ListTypes() []string {
	return m.repository.ListTypes()
}

func (m *manager) ListInstances(typeName string) []*TypeInstance {
	return m.repository.GetTypeInstances(typeName)
}

func generateManifestName() string {
	return fmt.Sprintf("manifest-%d", time.Now().UTC().UnixNano())
}

// Given a map of manifests, finds the largest time stamp, hence probably the latest manifest.
// This is a hack until we get a real story for storage.
func getLatestManifest(l map[string]*Manifest) *Manifest {
	var latest = 0
	var ret *Manifest
	for k, v := range l {
		var i = 0
		fmt.Sscanf(k, "manifest-%d", &i)
		if i > latest {
			latest = i
			ret = v
		}
	}
	return ret
}
<commit_msg>PutDeployment also uses createManifest and sets errors appropriately.<commit_after>/*
Copyright 2015 The Kubernetes Authors All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package manager

import (
	"fmt"
	"log"
	"time"
)

// Manager manages a persistent set of Deployments.
type Manager interface {
	ListDeployments() ([]Deployment, error)
	GetDeployment(name string) (*Deployment, error)
	CreateDeployment(t *Template) (*Deployment, error)
	DeleteDeployment(name string, forget bool) (*Deployment, error)
	PutDeployment(name string, t *Template) (*Deployment, error)
	ListManifests(deploymentName string) (map[string]*Manifest, error)
	GetManifest(deploymentName string, manifest string) (*Manifest, error)
	Expand(t *Template) (*Manifest, error)
	ListTypes() []string
	ListInstances(typeName string) []*TypeInstance
}

type manager struct {
	expander   Expander
	deployer   Deployer
	repository Repository
}

// NewManager returns a new initialized Manager.
func NewManager(expander Expander, deployer Deployer, repository Repository) Manager {
	return &manager{expander, deployer, repository}
}

// ListDeployments returns the list of deployments
func (m *manager) ListDeployments() ([]Deployment, error) {
	l, err := m.repository.ListDeployments()
	if err != nil {
		return nil, err
	}
	return l, nil
}

// GetDeployment retrieves the configuration stored for a given deployment
// as well as the current configuration from the cluster.
func (m *manager) GetDeployment(name string) (*Deployment, error) {
	d, err := m.repository.GetDeployment(name)
	if err != nil {
		return nil, err
	}
	latest := getLatestManifest(d.Manifests)
	if latest != nil {
		d.Current = latest.ExpandedConfig
	}
	return d, nil
}

// ListManifests retrieves the manifests for a given deployment
// of each of the deployments in the repository and returns the deployments.
func (m *manager) ListManifests(deploymentName string) (map[string]*Manifest, error) {
	l, err := m.repository.ListManifests(deploymentName)
	if err != nil {
		return nil, err
	}
	return l, nil
}

// GetManifest retrieves the specified manifest for a given deployment
func (m *manager) GetManifest(deploymentName string, manifestName string) (*Manifest, error) {
	d, err := m.repository.GetManifest(deploymentName, manifestName)
	if err != nil {
		return nil, err
	}
	return d, nil
}

// CreateDeployment expands the supplied template, creates the resulting
// configuration in the cluster, creates a new deployment that tracks it,
// and stores the deployment in the repository. Returns the deployment.
func (m *manager) CreateDeployment(t *Template) (*Deployment, error) {
	log.Printf("Creating deployment: %s", t.Name)
	_, err := m.repository.CreateDeployment(t.Name)
	if err != nil {
		log.Printf("CreateDeployment failed %v", err)
		return nil, err
	}

	manifest, err := m.createManifest(t)
	if err != nil {
		log.Printf("Manifest creation failed: %v", err)
		m.repository.SetDeploymentStatus(t.Name, FailedStatus)
		return nil, err
	}

	err = m.repository.AddManifest(t.Name, manifest)
	if err != nil {
		log.Printf("AddManifest failed %v", err)
		m.repository.SetDeploymentStatus(t.Name, FailedStatus)
		return nil, err
	}

	if err := m.deployer.CreateConfiguration(manifest.ExpandedConfig); err != nil {
		// Deployment failed, mark as deleted
		log.Printf("CreateConfiguration failed: %v", err)
		m.repository.SetDeploymentStatus(t.Name, FailedStatus)
		return nil, err
	}

	m.repository.SetDeploymentStatus(t.Name, DeployedStatus)
	// Finally update the type instances for this deployment.
	m.addTypeInstances(t.Name, manifest.Name, manifest.Layout)
	return m.repository.GetValidDeployment(t.Name)
}

func (m *manager) createManifest(t *Template) (*Manifest, error) {
	et, err := m.expander.ExpandTemplate(*t)
	if err != nil {
		log.Printf("Expansion failed %v", err)
		return nil, err
	}

	return &Manifest{
		Name:           generateManifestName(),
		Deployment:     t.Name,
		InputConfig:    t,
		ExpandedConfig: et.Config,
		Layout:         et.Layout,
	}, nil
}

func (m *manager) addTypeInstances(deploymentName string, manifestName string, layout *Layout) {
	m.repository.ClearTypeInstances(deploymentName)

	instances := make(map[string][]*TypeInstance)
	for i, r := range layout.Resources {
		addTypeInstances(&instances, r, deploymentName, manifestName, fmt.Sprintf("$.resources[%d]", i))
	}

	m.repository.SetTypeInstances(deploymentName, instances)
}

func addTypeInstances(instances *map[string][]*TypeInstance, r *LayoutResource, deploymentName string, manifestName string, jsonPath string) {
	// Add this resource.
	inst := &TypeInstance{
		Name:       r.Name,
		Type:       r.Type,
		Deployment: deploymentName,
		Manifest:   manifestName,
		Path:       jsonPath,
	}
	(*instances)[r.Type] = append((*instances)[r.Type], inst)

	// Add all sub resources if they exist.
	for i, sr := range r.Resources {
		addTypeInstances(instances, sr, deploymentName, manifestName, fmt.Sprintf("%s.resources[%d]", jsonPath, i))
	}
}

// DeleteDeployment deletes the configuration for the deployment with
// the supplied identifier from the cluster.repository. If forget is true, then
// the deployment is removed from the repository. Otherwise, it is marked
// as deleted and retained.
func (m *manager) DeleteDeployment(name string, forget bool) (*Deployment, error) {
	log.Printf("Deleting deployment: %s", name)
	d, err := m.repository.GetValidDeployment(name)
	if err != nil {
		return nil, err
	}

	// If there's a latest manifest, delete the underlying resources.
	latest := getLatestManifest(d.Manifests)
	if latest != nil {
		log.Printf("Deleting resources from the latest manifest")
		if err := m.deployer.DeleteConfiguration(latest.ExpandedConfig); err != nil {
			log.Printf("Failed to delete resources from the latest manifest: %v", err)
			return nil, err
		}

		// Create an empty manifest since resources have been deleted.
		err = m.repository.AddManifest(name, &Manifest{Deployment: name, Name: generateManifestName()})
		if err != nil {
			log.Printf("Failed to add empty manifest")
			return nil, err
		}
	}

	d, err = m.repository.DeleteDeployment(name, forget)
	if err != nil {
		return nil, err
	}

	// Finally remove the type instances for this deployment.
	m.repository.ClearTypeInstances(name)

	return d, nil
}

// PutDeployment replaces the configuration of the deployment with
// the supplied identifier in the cluster, and returns the deployment.
func (m *manager) PutDeployment(name string, t *Template) (*Deployment, error) {
	_, err := m.repository.GetValidDeployment(name)
	if err != nil {
		return nil, err
	}

	manifest, err := m.createManifest(t)
	if err != nil {
		log.Printf("Manifest creation failed: %v", err)
		m.repository.SetDeploymentStatus(name, FailedStatus)
		return nil, err
	}

	err = m.repository.AddManifest(t.Name, manifest)
	if err != nil {
		m.repository.SetDeploymentStatus(name, FailedStatus)
		return nil, err
	}

	if err := m.deployer.PutConfiguration(manifest.ExpandedConfig); err != nil {
		m.repository.SetDeploymentStatus(name, FailedStatus)
		return nil, err
	}

	// Finally update the type instances for this deployment.
	m.addTypeInstances(t.Name, manifest.Name, manifest.Layout)

	return m.repository.GetValidDeployment(t.Name)
}

func (m *manager) Expand(t *Template) (*Manifest, error) {
	et, err := m.expander.ExpandTemplate(*t)
	if err != nil {
		log.Printf("Expansion failed %v", err)
		return nil, err
	}

	return &Manifest{
		ExpandedConfig: et.Config,
		Layout:         et.Layout,
	}, nil
}

func (m *manager) ListTypes() []string {
	return m.repository.ListTypes()
}

func (m *manager) ListInstances(typeName string) []*TypeInstance {
	return m.repository.GetTypeInstances(typeName)
}

func generateManifestName() string {
	return fmt.Sprintf("manifest-%d", time.Now().UTC().UnixNano())
}

// Given a map of manifests, finds the largest time stamp, hence probably the latest manifest.
// This is a hack until we get a real story for storage.
func getLatestManifest(l map[string]*Manifest) *Manifest {
	var latest = 0
	var ret *Manifest
	for k, v := range l {
		var i = 0
		fmt.Sscanf(k, "manifest-%d", &i)
		if i > latest {
			latest = i
			ret = v
		}
	}
	return ret
}
<|endoftext|>


<commit_before>package avs

import (
	"strings"
	"time"
)

// Alert represents a single alarm or timer with a scheduled time.
type Alert struct {
	Token         string    `json:"token"`
	Type          AlertType `json:"type"`
	ScheduledTime string    `json:"scheduledTime"`
}

// AlertType specifies the type of an alert.
type AlertType string

// Possible values for AlertType, used by the SetAlert directive.
const (
	// AlertTypeAlarm specifies the type for an alarm. Alarms are scheduled for
	// specific times (e.g., to wake the user up).
	AlertTypeAlarm = AlertType("ALARM")
	// AlertTypeTimer specifies the type for a timer. Timers count down a certain
	// amount of time (e.g., "timer for 5 minutes").
	AlertTypeTimer = AlertType("TIMER")
)

// AudioItem represents an attached or streamable audio item.
type AudioItem struct {
	AudioItemId string `json:"audioItemId"`
	Stream      Stream `json:"stream"`
}

// ClearBehavior specifies how the play queue should be cleared.
type ClearBehavior string

// Possible values for ClearBehavior.
const (
	// ClearBehaviorClearAll clears all items in the queue, including the current
	// one.
	ClearBehaviorClearAll = ClearBehavior("CLEAR_ALL")
	// ClearBehaviorClearEnqueued clears all queued items in the queue (not
	// including the current one).
	ClearBehaviorClearEnqueued = ClearBehavior("CLEAR_ENQUEUED")
)

// ErrorType specifies the types of errors that the client may report to AVS.
type ErrorType string

// Possible values for ErrorType.
const (
	// ErrorTypeInternalError should be reported when none of the other error
	// types is applicable.
	ErrorTypeInternalError = ErrorType("INTERNAL_ERROR")
	// ErrorTypeUnexpectedInformation should be reported when the client is unable
	// to handle the received directive due to invalid format or data.
	ErrorTypeUnexpectedInformation = ErrorType("UNEXPECTED_INFORMATION_RECEIVED")
	// ErrorTypeUnsupportedOperation should be reported when the client is unable
	// to perform the operation specified by the directive.
	ErrorTypeUnsupportedOperation = ErrorType("UNSUPPORTED_OPERATION")
)

type MediaErrorType string

const (
	MediaErrorTypeInternalDeviceError = MediaErrorType("MEDIA_ERROR_INTERNAL_DEVICE_ERROR")
	MediaErrorTypeInternalServerError = MediaErrorType("MEDIA_ERROR_INTERNAL_SERVER_ERROR")
	MediaErrorTypeInvalidRequest      = MediaErrorType("MEDIA_ERROR_INVALID_REQUEST")
	MediaErrorTypeServiceUnavailable  = MediaErrorType("MEDIA_ERROR_SERVICE_UNAVAILABLE")
	MediaErrorTypeUnknown             = MediaErrorType("MEDIA_ERROR_UNKNOWN")
)

// PlayBehavior specifies how an audio item should be inserted into the play
// queue.
type PlayBehavior string

// Possible values for PlayBehavior.
const (
	// PlayBehaviorEnqueue specifies that the audio should be played after current
	// queue of audio.
	PlayBehaviorEnqueue = PlayBehavior("ENQUEUE")
	// PlayBehaviorReplaceAll specifies that the audio should play immediately,
	// throwing away all queued audio.
	PlayBehaviorReplaceAll = PlayBehavior("REPLACE_ALL")
	// PlayBehaviorReplaceEnqueued specifies that the audio should play after the
	// currently playing audio, replacing all queued audio.
	PlayBehaviorReplaceEnqueued = PlayBehavior("REPLACE_ENQUEUED")
)

// PlayerActivity specifies what state the audio player is in.
type PlayerActivity string

// Possible values for PlayerActivity.
const (
	PlayerActivityBufferUnderrun = PlayerActivity("BUFFER_UNDERRUN")
	PlayerActivityIdle           = PlayerActivity("IDLE")
	PlayerActivityPaused         = PlayerActivity("PAUSED")
	PlayerActivityPlaying        = PlayerActivity("PLAYING")
	PlayerActivityFinished       = PlayerActivity("FINISHED")
)

type ProgressReport struct {
	ProgressReportIntervalInMilliseconds float64 `json:"progressReportIntervalInMilliseconds"`
}

func (p *ProgressReport) Interval() time.Duration {
	return time.Duration(p.ProgressReportIntervalInMilliseconds) * time.Millisecond
}

// An audio stream which can either be attached with the response or a remote URL.
type Stream struct {
	ExpiryTime           string         `json:"expiryTime"`
	OffsetInMilliseconds float64        `json:"offsetInMilliseconds"`
	ProgressReport       ProgressReport `json:"progressReport"`
	Token                string         `json:"token"`
	URL                  string         `json:"url"`
}

// ContentId returns the content id of the audio, if it's attached with the
// response; otherwise, an empty string.
func (s *Stream) ContentId() string {
	if !strings.HasPrefix(s.URL, "cid:") {
		return ""
	}
	return s.URL[4:]
}
<commit_msg>Add playerActivity STOPPED<commit_after>package avs

import (
	"strings"
	"time"
)

// Alert represents a single alarm or timer with a scheduled time.
type Alert struct {
	Token         string    `json:"token"`
	Type          AlertType `json:"type"`
	ScheduledTime string    `json:"scheduledTime"`
}

// AlertType specifies the type of an alert.
type AlertType string

// Possible values for AlertType, used by the SetAlert directive.
const (
	// AlertTypeAlarm specifies the type for an alarm. Alarms are scheduled for
	// specific times (e.g., to wake the user up).
	AlertTypeAlarm = AlertType("ALARM")
	// AlertTypeTimer specifies the type for a timer. Timers count down a certain
	// amount of time (e.g., "timer for 5 minutes").
	AlertTypeTimer = AlertType("TIMER")
)

// AudioItem represents an attached or streamable audio item.
type AudioItem struct {
	AudioItemId string `json:"audioItemId"`
	Stream      Stream `json:"stream"`
}

// ClearBehavior specifies how the play queue should be cleared.
type ClearBehavior string

// Possible values for ClearBehavior.
const (
	// ClearBehaviorClearAll clears all items in the queue, including the current
	// one.
	ClearBehaviorClearAll = ClearBehavior("CLEAR_ALL")
	// ClearBehaviorClearEnqueued clears all queued items in the queue (not
	// including the current one).
	ClearBehaviorClearEnqueued = ClearBehavior("CLEAR_ENQUEUED")
)

// ErrorType specifies the types of errors that the client may report to AVS.
type ErrorType string

// Possible values for ErrorType.
const (
	// ErrorTypeInternalError should be reported when none of the other error
	// types is applicable.
	ErrorTypeInternalError = ErrorType("INTERNAL_ERROR")
	// ErrorTypeUnexpectedInformation should be reported when the client is unable
	// to handle the received directive due to invalid format or data.
	ErrorTypeUnexpectedInformation = ErrorType("UNEXPECTED_INFORMATION_RECEIVED")
	// ErrorTypeUnsupportedOperation should be reported when the client is unable
	// to perform the operation specified by the directive.
	ErrorTypeUnsupportedOperation = ErrorType("UNSUPPORTED_OPERATION")
)

type MediaErrorType string

const (
	MediaErrorTypeInternalDeviceError = MediaErrorType("MEDIA_ERROR_INTERNAL_DEVICE_ERROR")
	MediaErrorTypeInternalServerError = MediaErrorType("MEDIA_ERROR_INTERNAL_SERVER_ERROR")
	MediaErrorTypeInvalidRequest      = MediaErrorType("MEDIA_ERROR_INVALID_REQUEST")
	MediaErrorTypeServiceUnavailable  = MediaErrorType("MEDIA_ERROR_SERVICE_UNAVAILABLE")
	MediaErrorTypeUnknown             = MediaErrorType("MEDIA_ERROR_UNKNOWN")
)

// PlayBehavior specifies how an audio item should be inserted into the play
// queue.
type PlayBehavior string

// Possible values for PlayBehavior.
const (
	// PlayBehaviorEnqueue specifies that the audio should be played after current
	// queue of audio.
	PlayBehaviorEnqueue = PlayBehavior("ENQUEUE")
	// PlayBehaviorReplaceAll specifies that the audio should play immediately,
	// throwing away all queued audio.
	PlayBehaviorReplaceAll = PlayBehavior("REPLACE_ALL")
	// PlayBehaviorReplaceEnqueued specifies that the audio should play after the
	// currently playing audio, replacing all queued audio.
	PlayBehaviorReplaceEnqueued = PlayBehavior("REPLACE_ENQUEUED")
)

// PlayerActivity specifies what state the audio player is in.
type PlayerActivity string

// Possible values for PlayerActivity.
const (
	PlayerActivityBufferUnderrun = PlayerActivity("BUFFER_UNDERRUN")
	PlayerActivityIdle           = PlayerActivity("IDLE")
	PlayerActivityPaused         = PlayerActivity("PAUSED")
	PlayerActivityStopped        = PlayerActivity("STOPPED")
	PlayerActivityPlaying        = PlayerActivity("PLAYING")
	PlayerActivityFinished       = PlayerActivity("FINISHED")
)

type ProgressReport struct {
	ProgressReportIntervalInMilliseconds float64 `json:"progressReportIntervalInMilliseconds"`
}

func (p *ProgressReport) Interval() time.Duration {
	return time.Duration(p.ProgressReportIntervalInMilliseconds) * time.Millisecond
}

// An audio stream which can either be attached with the response or a remote URL.
type Stream struct {
	ExpiryTime           string         `json:"expiryTime"`
	OffsetInMilliseconds float64        `json:"offsetInMilliseconds"`
	ProgressReport       ProgressReport `json:"progressReport"`
	Token                string         `json:"token"`
	URL                  string         `json:"url"`
}

// ContentId returns the content id of the audio, if it's attached with the
// response; otherwise, an empty string.
func (s *Stream) ContentId() string {
	if !strings.HasPrefix(s.URL, "cid:") {
		return ""
	}
	return s.URL[4:]
}
<|endoftext|>


<commit_before>package main

import	(
	"os"
	"fmt"
	"crypto/sha512"
	"encoding/hex"
	"hash"
	"path/filepath"
	"flag"
	"net/http"
	"net/url"
	"io/ioutil"
	"log"
	"strconv"
)

type LMVFile struct {
	hash string
	size int64
	name string
}

func CalculateSHA512(str string) string {

	var hasher hash.Hash = sha512.New()

	hasher.Reset()
	hasher.Write([]byte(str))
	return hex.EncodeToString(hasher.Sum(nil))

}

func encode(fp string, token bool) {

	lmv_file := new(LMVFile)

	file, err := os.Open(fp)

    if err != nil {
    	// handle error
        return
    }

    defer file.Close()

    stat, err := file.Stat()
    if err != nil {
        return
    }

    bs := make([]byte, stat.Size())
    _, err = file.Read(bs)
    if err != nil {
        return
    }

    lmv_file.hash = CalculateSHA512(string(bs))
    lmv_file.size = stat.Size()
    lmv_file.name = filepath.Base(fp)

	if token {

    	upload_address := "http://127.0.0.1:8081/upload"

		fields := make(url.Values)
        fields.Set("name", lmv_file.name)
        fields.Set("hash", lmv_file.hash)
        fields.Set("size", strconv.FormatInt(lmv_file.size, 10))

    	resp, err := http.PostForm(upload_address, fields)

    	if err != nil {
			// handle error
			log.Fatal(err)
		}

		defer resp.Body.Close()

		body, err := ioutil.ReadAll(resp.Body)

		if err != nil {
			return
		}

		fmt.Println("'" + lmv_file.name + "'" + " --> " + "'" + string(body) + "'")

	} else {

		os.Create(lmv_file.name + ".lmv")

		full := ""
		full += lmv_file.hash
		full += "\n"
		full += lmv_file.name
		full += "\n"
		full += strconv.FormatInt(lmv_file.size, 10)

		err = ioutil.WriteFile(lmv_file.name + ".lmv", []byte(full), 0644)
    	if err != nil { panic(err) }

    }

}

func main() {

	token := flag.Bool("token", false, "Use tokens in place of .lmv files")

	flag.Parse()

	if len(os.Args) < 2 {

		fmt.Println("Use lmv -h for usage")

	} else {

		for i := 0; i < len(os.Args[1:]); i++ {

			if _, err := os.Stat(os.Args[i+1]); err == nil {

	    		encode(os.Args[i+1], *token)

			}

	    }

	}
}<commit_msg>log.Fatal on error instead of panicking<commit_after>package main

import	(
	"os"
	"fmt"
	"crypto/sha512"
	"encoding/hex"
	"hash"
	"path/filepath"
	"flag"
	"net/http"
	"net/url"
	"io/ioutil"
	"log"
	"strconv"
)

type LMVFile struct {
	hash string
	size int64
	name string
}

func CalculateSHA512(str string) string {

	var hasher hash.Hash = sha512.New()

	hasher.Reset()
	hasher.Write([]byte(str))
	return hex.EncodeToString(hasher.Sum(nil))

}

func encode(fp string, token bool) {

	lmv_file := new(LMVFile)

	file, err := os.Open(fp)

    if err != nil {
    	log.Fatal(err)
    }

    defer file.Close()

    stat, err := file.Stat()

    if err != nil {
    	log.Fatal(err)
    }

    bs := make([]byte, stat.Size())
    _, err = file.Read(bs)

    if err != nil {
        log.Fatal(err)
    }

    lmv_file.hash = CalculateSHA512(string(bs))
    lmv_file.size = stat.Size()
    lmv_file.name = filepath.Base(fp)

	if token {

    	upload_address := "http://127.0.0.1:8081/upload"

		fields := make(url.Values)
        fields.Set("name", lmv_file.name)
        fields.Set("hash", lmv_file.hash)
        fields.Set("size", strconv.FormatInt(lmv_file.size, 10))

    	resp, err := http.PostForm(upload_address, fields)

    	if err != nil {
			log.Fatal(err)
		}

		defer resp.Body.Close()

		body, err := ioutil.ReadAll(resp.Body)

		if err != nil {
			log.Fatal(err)
		}

		fmt.Println("'" + lmv_file.name + "'" + " --> " + "'" + string(body) + "'")

	} else {

		os.Create(lmv_file.name + ".lmv")

		full := ""
		full += lmv_file.hash
		full += "\n"
		full += lmv_file.name
		full += "\n"
		full += strconv.FormatInt(lmv_file.size, 10)

		err = ioutil.WriteFile(lmv_file.name + ".lmv", []byte(full), 0644)

		if err != nil {
			log.Fatal(err)
		}

    }

}

func main() {

	token := flag.Bool("token", false, "Use tokens in place of .lmv files")

	flag.Parse()

	if len(os.Args) < 2 {

		fmt.Println("Use lmv -h for usage")

	} else {

		for i := 0; i < len(os.Args[1:]); i++ {

			if _, err := os.Stat(os.Args[i+1]); err == nil {

	    		encode(os.Args[i+1], *token)

			}

	    }

	}
}<|endoftext|>


<commit_before>package dockerclient

import (
	"time"
)

type ContainerConfig struct {
	Hostname        string
	Domainname      string
	User            string
	Memory          int64
	MemorySwap      int64
	CpuShares       int64
	Cpuset          string
	AttachStdin     bool
	AttachStdout    bool
	AttachStderr    bool
	PortSpecs       []string
	ExposedPorts    map[string]struct{}
	Tty             bool
	OpenStdin       bool
	StdinOnce       bool
	Env             []string
	Cmd             []string
	Image           string
	Labels          map[string]string
	Volumes         map[string]struct{}
	WorkingDir      string
	Entrypoint      []string
	NetworkDisabled bool
	OnBuild         []string

	// This is used only by the create command
	HostConfig HostConfig
}

type HostConfig struct {
	Binds           []string
	ContainerIDFile string
	LxcConf         []map[string]string
	Privileged      bool
	PortBindings    map[string][]PortBinding
	Links           []string
	PublishAllPorts bool
	Dns             []string
	DnsSearch       []string
	VolumesFrom     []string
	SecurityOpt     []string
	NetworkMode     string
	RestartPolicy   RestartPolicy
}

type ExecConfig struct {
	AttachStdin  bool
	AttachStdout bool
	AttachStderr bool
	Tty          bool
	Cmd          []string
	Container    string
	Detach       bool
}

type LogOptions struct {
	Follow     bool
	Stdout     bool
	Stderr     bool
	Timestamps bool
	Tail       int64
}

type RestartPolicy struct {
	Name              string
	MaximumRetryCount int64
}

type PortBinding struct {
	HostIp   string
	HostPort string
}

type ContainerInfo struct {
	Id      string
	Created string
	Path    string
	Name    string
	Args    []string
	ExecIDs []string
	Config  *ContainerConfig
	State   struct {
		Running    bool
		Paused     bool
		Restarting bool
		Pid        int
		ExitCode   int
		StartedAt  time.Time
		FinishedAt time.Time
		Ghost      bool
	}
	Image           string
	NetworkSettings struct {
		IpAddress   string
		IpPrefixLen int
		Gateway     string
		Bridge      string
		Ports       map[string][]PortBinding
	}
	SysInitPath    string
	ResolvConfPath string
	Volumes        map[string]string
	HostConfig     *HostConfig
}

type ContainerChanges struct {
	Path string
	Kind int
}

type Port struct {
	IP          string
	PrivatePort int
	PublicPort  int
	Type        string
}

type Container struct {
	Id         string
	Names      []string
	Image      string
	Command    string
	Created    int64
	Status     string
	Ports      []Port
	SizeRw     int64
	SizeRootFs int64
}

type Event struct {
	Id     string
	Status string
	From   string
	Time   int64
}

type Version struct {
	Version   string
	GitCommit string
	GoVersion string
}

type RespContainersCreate struct {
	Id       string
	Warnings []string
}

type Image struct {
	Created     int64
	Id          string
	ParentId    string
	RepoTags    []string
	Size        int64
	VirtualSize int64
}

type Info struct {
	ID              string
	Containers      int64
	Driver          string
	DriverStatus    [][]string
	ExecutionDriver string
	Images          int64
	KernelVersion   string
	OperatingSystem string
	NCPU            int64
	MemTotal        int64
	Name            string
	Labels          []string
}

type ImageDelete struct {
	Deleted  string
	Untagged string
}

// The following are types for the API stats endpoint
type ThrottlingData struct {
	// Number of periods with throttling active
	Periods uint64 `json:"periods"`
	// Number of periods when the container hit its throttling limit.
	ThrottledPeriods uint64 `json:"throttled_periods"`
	// Aggregate time the container was throttled for in nanoseconds.
	ThrottledTime uint64 `json:"throttled_time"`
}

// Stats types below
// All CPU stats are aggregated since container inception.
type CpuUsage struct {
	// Total CPU time consumed.
	// Units: nanoseconds.
	TotalUsage uint64 `json:"total_usage"`
	// Total CPU time consumed per core.
	// Units: nanoseconds.
	PercpuUsage []uint64 `json:"percpu_usage"`
	// Time spent by tasks of the cgroup in kernel mode.
	// Units: nanoseconds.
	UsageInKernelmode uint64 `json:"usage_in_kernelmode"`
	// Time spent by tasks of the cgroup in user mode.
	// Units: nanoseconds.
	UsageInUsermode uint64 `json:"usage_in_usermode"`
}

type CpuStats struct {
	CpuUsage       CpuUsage       `json:"cpu_usage"`
	SystemUsage    uint64         `json:"system_cpu_usage"`
	ThrottlingData ThrottlingData `json:"throttling_data,omitempty"`
}

type NetworkStats struct {
	RxBytes   uint64 `json:"rx_bytes"`
	RxPackets uint64 `json:"rx_packets"`
	RxErrors  uint64 `json:"rx_errors"`
	RxDropped uint64 `json:"rx_dropped"`
	TxBytes   uint64 `json:"tx_bytes"`
	TxPackets uint64 `json:"tx_packets"`
	TxErrors  uint64 `json:"tx_errors"`
	TxDropped uint64 `json:"tx_dropped"`
}

type MemoryStats struct {
	Usage    uint64            `json:"usage"`
	MaxUsage uint64            `json:"max_usage"`
	Stats    map[string]uint64 `json:"stats"`
	Failcnt  uint64            `json:"failcnt"`
	Limit    uint64            `json:"limit"`
}

type BlkioStatEntry struct {
	Major uint64 `json:"major"`
	Minor uint64 `json:"minor"`
	Op    string `json:"op"`
	Value uint64 `json:"value"`
}

type BlkioStats struct {
	// number of bytes tranferred to and from the block device
	IoServiceBytesRecursive []BlkioStatEntry `json:"io_service_bytes_recursive"`
	IoServicedRecursive     []BlkioStatEntry `json:"io_serviced_recursive"`
	IoQueuedRecursive       []BlkioStatEntry `json:"io_queue_recursive"`
	IoServiceTimeRecursive  []BlkioStatEntry `json:"io_service_time_recursive"`
	IoWaitTimeRecursive     []BlkioStatEntry `json:"io_wait_time_recursive"`
	IoMergedRecursive       []BlkioStatEntry `json:"io_merged_recursive"`
	IoTimeRecursive         []BlkioStatEntry `json:"io_time_recursive"`
	SectorsRecursive        []BlkioStatEntry `json:"sectors_recursive"`
}

type Stats struct {
	Read         time.Time    `json:"read"`
	NetworkStats NetworkStats `json:"network,omitempty"`
	CpuStats     CpuStats     `json:"cpu_stats,omitempty"`
	MemoryStats  MemoryStats  `json:"memory_stats,omitempty"`
	BlkioStats   BlkioStats   `json:"blkio_stats,omitempty"`
}
<commit_msg>remove comment<commit_after>package dockerclient

import (
	"time"
)

type ContainerConfig struct {
	Hostname        string
	Domainname      string
	User            string
	Memory          int64
	MemorySwap      int64
	CpuShares       int64
	Cpuset          string
	AttachStdin     bool
	AttachStdout    bool
	AttachStderr    bool
	PortSpecs       []string
	ExposedPorts    map[string]struct{}
	Tty             bool
	OpenStdin       bool
	StdinOnce       bool
	Env             []string
	Cmd             []string
	Image           string
	Labels          map[string]string
	Volumes         map[string]struct{}
	WorkingDir      string
	Entrypoint      []string
	NetworkDisabled bool
	OnBuild         []string

	// This is used only by the create command
	HostConfig HostConfig
}

type HostConfig struct {
	Binds           []string
	ContainerIDFile string
	LxcConf         []map[string]string
	Privileged      bool
	PortBindings    map[string][]PortBinding
	Links           []string
	PublishAllPorts bool
	Dns             []string
	DnsSearch       []string
	VolumesFrom     []string
	SecurityOpt     []string
	NetworkMode     string
	RestartPolicy   RestartPolicy
}

type ExecConfig struct {
	AttachStdin  bool
	AttachStdout bool
	AttachStderr bool
	Tty          bool
	Cmd          []string
	Container    string
	Detach       bool
}

type LogOptions struct {
	Follow     bool
	Stdout     bool
	Stderr     bool
	Timestamps bool
	Tail       int64
}

type RestartPolicy struct {
	Name              string
	MaximumRetryCount int64
}

type PortBinding struct {
	HostIp   string
	HostPort string
}

type ContainerInfo struct {
	Id      string
	Created string
	Path    string
	Name    string
	Args    []string
	ExecIDs []string
	Config  *ContainerConfig
	State   struct {
		Running    bool
		Paused     bool
		Restarting bool
		Pid        int
		ExitCode   int
		StartedAt  time.Time
		FinishedAt time.Time
		Ghost      bool
	}
	Image           string
	NetworkSettings struct {
		IpAddress   string
		IpPrefixLen int
		Gateway     string
		Bridge      string
		Ports       map[string][]PortBinding
	}
	SysInitPath    string
	ResolvConfPath string
	Volumes        map[string]string
	HostConfig     *HostConfig
}

type ContainerChanges struct {
	Path string
	Kind int
}

type Port struct {
	IP          string
	PrivatePort int
	PublicPort  int
	Type        string
}

type Container struct {
	Id         string
	Names      []string
	Image      string
	Command    string
	Created    int64
	Status     string
	Ports      []Port
	SizeRw     int64
	SizeRootFs int64
}

type Event struct {
	Id     string
	Status string
	From   string
	Time   int64
}

type Version struct {
	Version   string
	GitCommit string
	GoVersion string
}

type RespContainersCreate struct {
	Id       string
	Warnings []string
}

type Image struct {
	Created     int64
	Id          string
	ParentId    string
	RepoTags    []string
	Size        int64
	VirtualSize int64
}

type Info struct {
	ID              string
	Containers      int64
	Driver          string
	DriverStatus    [][]string
	ExecutionDriver string
	Images          int64
	KernelVersion   string
	OperatingSystem string
	NCPU            int64
	MemTotal        int64
	Name            string
	Labels          []string
}

type ImageDelete struct {
	Deleted  string
	Untagged string
}

// The following are types for the API stats endpoint
type ThrottlingData struct {
	// Number of periods with throttling active
	Periods uint64 `json:"periods"`
	// Number of periods when the container hit its throttling limit.
	ThrottledPeriods uint64 `json:"throttled_periods"`
	// Aggregate time the container was throttled for in nanoseconds.
	ThrottledTime uint64 `json:"throttled_time"`
}

// All CPU stats are aggregated since container inception.
type CpuUsage struct {
	// Total CPU time consumed.
	// Units: nanoseconds.
	TotalUsage uint64 `json:"total_usage"`
	// Total CPU time consumed per core.
	// Units: nanoseconds.
	PercpuUsage []uint64 `json:"percpu_usage"`
	// Time spent by tasks of the cgroup in kernel mode.
	// Units: nanoseconds.
	UsageInKernelmode uint64 `json:"usage_in_kernelmode"`
	// Time spent by tasks of the cgroup in user mode.
	// Units: nanoseconds.
	UsageInUsermode uint64 `json:"usage_in_usermode"`
}

type CpuStats struct {
	CpuUsage       CpuUsage       `json:"cpu_usage"`
	SystemUsage    uint64         `json:"system_cpu_usage"`
	ThrottlingData ThrottlingData `json:"throttling_data,omitempty"`
}

type NetworkStats struct {
	RxBytes   uint64 `json:"rx_bytes"`
	RxPackets uint64 `json:"rx_packets"`
	RxErrors  uint64 `json:"rx_errors"`
	RxDropped uint64 `json:"rx_dropped"`
	TxBytes   uint64 `json:"tx_bytes"`
	TxPackets uint64 `json:"tx_packets"`
	TxErrors  uint64 `json:"tx_errors"`
	TxDropped uint64 `json:"tx_dropped"`
}

type MemoryStats struct {
	Usage    uint64            `json:"usage"`
	MaxUsage uint64            `json:"max_usage"`
	Stats    map[string]uint64 `json:"stats"`
	Failcnt  uint64            `json:"failcnt"`
	Limit    uint64            `json:"limit"`
}

type BlkioStatEntry struct {
	Major uint64 `json:"major"`
	Minor uint64 `json:"minor"`
	Op    string `json:"op"`
	Value uint64 `json:"value"`
}

type BlkioStats struct {
	// number of bytes tranferred to and from the block device
	IoServiceBytesRecursive []BlkioStatEntry `json:"io_service_bytes_recursive"`
	IoServicedRecursive     []BlkioStatEntry `json:"io_serviced_recursive"`
	IoQueuedRecursive       []BlkioStatEntry `json:"io_queue_recursive"`
	IoServiceTimeRecursive  []BlkioStatEntry `json:"io_service_time_recursive"`
	IoWaitTimeRecursive     []BlkioStatEntry `json:"io_wait_time_recursive"`
	IoMergedRecursive       []BlkioStatEntry `json:"io_merged_recursive"`
	IoTimeRecursive         []BlkioStatEntry `json:"io_time_recursive"`
	SectorsRecursive        []BlkioStatEntry `json:"sectors_recursive"`
}

type Stats struct {
	Read         time.Time    `json:"read"`
	NetworkStats NetworkStats `json:"network,omitempty"`
	CpuStats     CpuStats     `json:"cpu_stats,omitempty"`
	MemoryStats  MemoryStats  `json:"memory_stats,omitempty"`
	BlkioStats   BlkioStats   `json:"blkio_stats,omitempty"`
}
<|endoftext|>


<commit_before>package stump

import (
	"fmt"
	"io"
	"os"
	"strings"
)

var Verbose bool

var ErrorPrefix = "ERROR: "

var LogOut io.Writer = os.Stdout
var ErrOut io.Writer = os.Stdout

func Error(args ...interface{}) {
	log(ErrOut, ErrorPrefix, args)
}

func Fatal(args ...interface{}) {
	Error(args...)
	os.Exit(1)
}

func Log(args ...interface{}) {
	log(LogOut, "", args)
}

func VLog(args ...interface{}) {
	if Verbose {
		log(LogOut, "", args)
	}
}

func log(out io.Writer, prefix string, args []interface{}) {
	prefix = strings.TrimRight(prefix, "\t \n")
	writelog := func(format string, args ...interface{}) {
		n := strings.Count(format, "%")
		if n < len(args) {
			format += strings.Repeat(" %s", len(args)-n)
		}
		if format[len(format)-1] != '\n' {
			format += "\n"
		}
		fmt.Fprintf(out, format, args...)
	}

	if len(args) == 0 {
		writelog(prefix)
		return
	}

	switch s := args[0].(type) {
	case string:
		writelog(prefix+s, args[1:]...)
	case fmt.Stringer:
		writelog(prefix+s.String(), args[1:]...)
	default:
		format := strings.Repeat("%s ", len(args))
		writelog(prefix+format, args...)
	}
}
<commit_msg>prefixes can have spaces<commit_after>package stump

import (
	"fmt"
	"io"
	"os"
	"strings"
)

var Verbose bool

var ErrorPrefix = "ERROR: "

var LogOut io.Writer = os.Stdout
var ErrOut io.Writer = os.Stdout

func Error(args ...interface{}) {
	log(ErrOut, ErrorPrefix, args)
}

func Fatal(args ...interface{}) {
	Error(args...)
	os.Exit(1)
}

func Log(args ...interface{}) {
	log(LogOut, "", args)
}

func VLog(args ...interface{}) {
	if Verbose {
		log(LogOut, "", args)
	}
}

func log(out io.Writer, prefix string, args []interface{}) {
	writelog := func(format string, args ...interface{}) {
		n := strings.Count(format, "%")
		if n < len(args) {
			format += strings.Repeat(" %s", len(args)-n)
		}
		if format[len(format)-1] != '\n' {
			format += "\n"
		}
		fmt.Fprintf(out, format, args...)
	}

	if len(args) == 0 {
		writelog(prefix)
		return
	}

	switch s := args[0].(type) {
	case string:
		writelog(prefix+s, args[1:]...)
	case fmt.Stringer:
		writelog(prefix+s.String(), args[1:]...)
	default:
		format := strings.Repeat("%s ", len(args))
		writelog(prefix+format, args...)
	}
}
<|endoftext|>


<commit_before>package ext

import (
	"log"
	"os"
	"runtime"
)

type Trace bool

const (
	DEBUG = 2
	ERROR = 3
	FATAL = 4
)

var (
	tl          *log.Logger = log.New(os.Stdout, "[TRACE] ", log.LstdFlags)
	dl          *log.Logger = log.New(os.Stdout, "[DEBUG] ", log.LstdFlags)
	il          *log.Logger = log.New(os.Stdout, "[INFO] ", log.LstdFlags)
	el          *log.Logger = log.New(os.Stdout, "[ERROR] ", log.LstdFlags)
	TraceSwitch Trace
)

func init() {
}

func (t Trace) T() string {
	if t {
		p, _, _, ok := runtime.Caller(2)
		if ok {
			s := runtime.FuncForPC(p).Name()
			tl.Printf("--> [%s]\n", s)
			return s
		}
	}
	return ""
}

func (t Trace) UT(s string) {
	if t && len(s) > 0 {
		tl.Printf("<-- [%s]\n", s)
	}
}

func T() string {
	return TraceSwitch.T()
}

func UT(s string) {
	TraceSwitch.UT(s)
}

func LogDebug(format string, v ...interface{}) {
	dl.Printf(format, v...)
}

func LogInfo(format string, v ...interface{}) {
	il.Printf(format, v...)
}

func LogError(err error) error {
	el.Printf("%s\n%s", err.Error(), Stack())
	return err
}
<commit_msg>use grpc code<commit_after>package ext

import (
	"log"
	"os"
	"runtime"
)

type Trace bool

const (
	DEBUG = 2
	ERROR = 3
	FATAL = 4
)

var (
	tl          *log.Logger = log.New(os.Stdout, "[TRACE] ", log.LstdFlags)
	dl          *log.Logger = log.New(os.Stdout, "[DEBUG] ", log.LstdFlags)
	il          *log.Logger = log.New(os.Stdout, "[INFO] ", log.LstdFlags)
	el          *log.Logger = log.New(os.Stderr, "[ERROR] ", log.LstdFlags)
	TraceSwitch Trace
)

func init() {
}

func (t Trace) T() string {
	if t {
		p, _, _, ok := runtime.Caller(2)
		if ok {
			s := runtime.FuncForPC(p).Name()
			tl.Printf("--> [%s]\n", s)
			return s
		}
	}
	return ""
}

func (t Trace) UT(s string) {
	if t && len(s) > 0 {
		tl.Printf("<-- [%s]\n", s)
	}
}

func T() string {
	return TraceSwitch.T()
}

func UT(s string) {
	TraceSwitch.UT(s)
}

func LogDebug(format string, v ...interface{}) {
	dl.Printf(format, v...)
}

func LogInfo(format string, v ...interface{}) {
	il.Printf(format, v...)
}

func LogError(err error) error {
	el.Printf("%s\n%s", err.Error(), Stack())
	return err
}
<|endoftext|>


<commit_before>package main

import (
	"github.com/realglobe-Inc/go-lib-rg/rglog"
)

var log rglog.Logger

func init() {
	log = rglog.GetLogger("github.com/realglobe-Inc/edo/edo-access-proxy")
}
<commit_msg>ログライブラリの仕様変更への対応<commit_after>package main

import (
	"github.com/realglobe-Inc/go-lib-rg/rglog"
)

var log = rglog.Logger("github.com/realglobe-Inc/edo/edo-access-proxy")
<|endoftext|>


<commit_before>package log

import (
	"encoding/json"
	"fmt"
	"net/http"
	"os"
	"path/filepath"
	"runtime"
	"sync"
	"time"
)

type MsgType uint8
type OutType uint8

const (
	MessageLog         MsgType = 0
	Message2Log        MsgType = 1
	WarningLog         MsgType = 2
	DebugLog           MsgType = 3
	ErrorLog           MsgType = 4
	FormattedOut       OutType = 0
	LineOut            OutType = 1
	DefaultMaxLineSize int     = 2000
	DefaultTimeFormat  string  = "2006/01/02 15:04:05"
)

// AdapterFunc is the type for the function adapter
// any function that has this signature can be used as an adapter
type AdapterFunc func(m MsgType, o OutType, config map[string]string, msg ...interface{})

// AdapterPod contains the metadata of an adapter
type AdapterPod struct {
	Adapter AdapterFunc
	Config  map[string]string
}

var (
	// DebugMode Enable debug mode
	DebugMode bool

	// MaxLineSize limits the size of the line, if the size
	// exceeds that indicated by MaxLineSize the system cuts
	// the string and adds "..." at the end.
	MaxLineSize = DefaultMaxLineSize

	// TimeFormat defines which pattern will be applied for
	// display time in the logs.
	TimeFormat = DefaultTimeFormat

	// Colors contain color array
	Colors = []string{
		MessageLog:  "\x1b[37m", // White
		Message2Log: "\x1b[92m", // Light green
		WarningLog:  "\x1b[93m", // Light Yellow
		DebugLog:    "\x1b[96m", // Light Cyan
		ErrorLog:    "\x1b[91m", // Light Red
	}

	// Prefixes of messages
	Prefixes = []string{
		MessageLog:  "msg",
		Message2Log: "msg",
		WarningLog:  "warning",
		DebugLog:    "debug",
		ErrorLog:    "error",
	}

	now      = time.Now
	adapters = make(map[string]AdapterPod)
	lock     = sync.RWMutex{}
)

func init() {
	if len(adapters) == 0 {
		AddAdapter("stdout", AdapterPod{
			Adapter: pln,
			Config:  nil,
		})
	}
}

// AddAdapter allows to add an adapter and parameters
func AddAdapter(name string, adapter AdapterPod) {
	lock.Lock()
	adapters[name] = adapter
	lock.Unlock()
}

// RemoveAapter remove the adapter from list
func RemoveAapter(name string) {
	lock.Lock()
	delete(adapters, name)
	lock.Unlock()
}

// SetAdapterConfig allows set new adapter parameters
func SetAdapterConfig(name string, config map[string]string) {
	lock.Lock()
	a := adapters[name]
	a.Config = config
	adapters[name] = a
	lock.Unlock()
}

func runAdapters(m MsgType, o OutType, msg ...interface{}) {
	lock.RLock()
	defer lock.RUnlock()
	for _, a := range adapters {
		a.Adapter(m, o, a.Config, msg...)
	}
}

// HTTPError write lot to stdout and return json error on http.ResponseWriter with http error code.
func HTTPError(w http.ResponseWriter, code int) {
	msg := http.StatusText(code)
	Errorln(msg)
	m := make(map[string]string)
	m["status"] = "error"
	m["error"] = msg
	b, _ := json.MarshalIndent(m, "", "\t")
	http.Error(w, string(b), code)
}

// Fatal show message with line break at the end and exit to OS.
func Fatal(msg ...interface{}) {
	runAdapters(ErrorLog, LineOut, msg...)
	os.Exit(-1)
}

// Errorln message with line break at the end.
func Errorln(msg ...interface{}) {
	runAdapters(ErrorLog, LineOut, msg...)
}

// Errorf shows formatted error message on stdout without line break at the end.
func Errorf(msg ...interface{}) {
	runAdapters(ErrorLog, FormattedOut, msg...)
}

// Warningln shows warning message on stdout with line break at the end.
func Warningln(msg ...interface{}) {
	runAdapters(WarningLog, LineOut, msg...)
}

// Warningf shows formatted warning message on stdout without line break at the end.
func Warningf(msg ...interface{}) {
	runAdapters(WarningLog, FormattedOut, msg...)
}

// Println shows message on stdout with line break at the end.
func Println(msg ...interface{}) {
	runAdapters(MessageLog, LineOut, msg...)
}

// Printf shows formatted message on stdout without line break at the end.
func Printf(msg ...interface{}) {
	runAdapters(MessageLog, FormattedOut, msg...)
}

// Debugln shows debug message on stdout with line break at the end.
// If debug mode is not active no message is displayed
func Debugln(msg ...interface{}) {
	runAdapters(DebugLog, LineOut, msg...)
}

// Debugf shows debug message on stdout without line break at the end.
// If debug mode is not active no message is displayed
func Debugf(msg ...interface{}) {
	runAdapters(DebugLog, FormattedOut, msg...)
}

func pln(m MsgType, o OutType, config map[string]string, msg ...interface{}) {
	if m == DebugLog && !DebugMode {
		return
	}

	var debugInfo, lineBreak, output string

	if DebugMode {
		_, fn, line, _ := runtime.Caller(5)
		fn = filepath.Base(fn)
		debugInfo = fmt.Sprintf("%s:%d ", fn, line)
	}

	if o == FormattedOut {
		output = fmt.Sprintf(msg[0].(string), msg[1:]...)
	} else {
		output = fmt.Sprint(msg...)
		lineBreak = "\n"
	}

	output = fmt.Sprintf("%s%s [%s] %s%s\033[0;00m",
		Colors[m],
		now().UTC().Format(TimeFormat),
		Prefixes[m],
		debugInfo,
		output)

	if len(output) > MaxLineSize {
		output = output[:MaxLineSize] + "..."
	}
	output = output + lineBreak
	fmt.Print(output)
}
<commit_msg>group create type (#17)<commit_after>package log

import (
	"encoding/json"
	"fmt"
	"net/http"
	"os"
	"path/filepath"
	"runtime"
	"sync"
	"time"
)

type (
	MsgType uint8
	OutType uint8
)

const (
	MessageLog         MsgType = 0
	Message2Log        MsgType = 1
	WarningLog         MsgType = 2
	DebugLog           MsgType = 3
	ErrorLog           MsgType = 4
	FormattedOut       OutType = 0
	LineOut            OutType = 1
	DefaultMaxLineSize int     = 2000
	DefaultTimeFormat  string  = "2006/01/02 15:04:05"
)

// AdapterFunc is the type for the function adapter
// any function that has this signature can be used as an adapter
type AdapterFunc func(m MsgType, o OutType, config map[string]string, msg ...interface{})

// AdapterPod contains the metadata of an adapter
type AdapterPod struct {
	Adapter AdapterFunc
	Config  map[string]string
}

var (
	// DebugMode Enable debug mode
	DebugMode bool

	// MaxLineSize limits the size of the line, if the size
	// exceeds that indicated by MaxLineSize the system cuts
	// the string and adds "..." at the end.
	MaxLineSize = DefaultMaxLineSize

	// TimeFormat defines which pattern will be applied for
	// display time in the logs.
	TimeFormat = DefaultTimeFormat

	// Colors contain color array
	Colors = []string{
		MessageLog:  "\x1b[37m", // White
		Message2Log: "\x1b[92m", // Light green
		WarningLog:  "\x1b[93m", // Light Yellow
		DebugLog:    "\x1b[96m", // Light Cyan
		ErrorLog:    "\x1b[91m", // Light Red
	}

	// Prefixes of messages
	Prefixes = []string{
		MessageLog:  "msg",
		Message2Log: "msg",
		WarningLog:  "warning",
		DebugLog:    "debug",
		ErrorLog:    "error",
	}

	now      = time.Now
	adapters = make(map[string]AdapterPod)
	lock     = sync.RWMutex{}
)

func init() {
	if len(adapters) == 0 {
		AddAdapter("stdout", AdapterPod{
			Adapter: pln,
			Config:  nil,
		})
	}
}

// AddAdapter allows to add an adapter and parameters
func AddAdapter(name string, adapter AdapterPod) {
	lock.Lock()
	adapters[name] = adapter
	lock.Unlock()
}

// RemoveAapter remove the adapter from list
func RemoveAapter(name string) {
	lock.Lock()
	delete(adapters, name)
	lock.Unlock()
}

// SetAdapterConfig allows set new adapter parameters
func SetAdapterConfig(name string, config map[string]string) {
	lock.Lock()
	a := adapters[name]
	a.Config = config
	adapters[name] = a
	lock.Unlock()
}

func runAdapters(m MsgType, o OutType, msg ...interface{}) {
	lock.RLock()
	defer lock.RUnlock()
	for _, a := range adapters {
		a.Adapter(m, o, a.Config, msg...)
	}
}

// HTTPError write lot to stdout and return json error on http.ResponseWriter with http error code.
func HTTPError(w http.ResponseWriter, code int) {
	msg := http.StatusText(code)
	Errorln(msg)
	m := make(map[string]string)
	m["status"] = "error"
	m["error"] = msg
	b, _ := json.MarshalIndent(m, "", "\t")
	http.Error(w, string(b), code)
}

// Fatal show message with line break at the end and exit to OS.
func Fatal(msg ...interface{}) {
	runAdapters(ErrorLog, LineOut, msg...)
	os.Exit(-1)
}

// Errorln message with line break at the end.
func Errorln(msg ...interface{}) {
	runAdapters(ErrorLog, LineOut, msg...)
}

// Errorf shows formatted error message on stdout without line break at the end.
func Errorf(msg ...interface{}) {
	runAdapters(ErrorLog, FormattedOut, msg...)
}

// Warningln shows warning message on stdout with line break at the end.
func Warningln(msg ...interface{}) {
	runAdapters(WarningLog, LineOut, msg...)
}

// Warningf shows formatted warning message on stdout without line break at the end.
func Warningf(msg ...interface{}) {
	runAdapters(WarningLog, FormattedOut, msg...)
}

// Println shows message on stdout with line break at the end.
func Println(msg ...interface{}) {
	runAdapters(MessageLog, LineOut, msg...)
}

// Printf shows formatted message on stdout without line break at the end.
func Printf(msg ...interface{}) {
	runAdapters(MessageLog, FormattedOut, msg...)
}

// Debugln shows debug message on stdout with line break at the end.
// If debug mode is not active no message is displayed
func Debugln(msg ...interface{}) {
	runAdapters(DebugLog, LineOut, msg...)
}

// Debugf shows debug message on stdout without line break at the end.
// If debug mode is not active no message is displayed
func Debugf(msg ...interface{}) {
	runAdapters(DebugLog, FormattedOut, msg...)
}

func pln(m MsgType, o OutType, config map[string]string, msg ...interface{}) {
	if m == DebugLog && !DebugMode {
		return
	}

	var debugInfo, lineBreak, output string

	if DebugMode {
		_, fn, line, _ := runtime.Caller(5)
		fn = filepath.Base(fn)
		debugInfo = fmt.Sprintf("%s:%d ", fn, line)
	}

	if o == FormattedOut {
		output = fmt.Sprintf(msg[0].(string), msg[1:]...)
	} else {
		output = fmt.Sprint(msg...)
		lineBreak = "\n"
	}

	output = fmt.Sprintf("%s%s [%s] %s%s\033[0;00m",
		Colors[m],
		now().UTC().Format(TimeFormat),
		Prefixes[m],
		debugInfo,
		output)

	if len(output) > MaxLineSize {
		output = output[:MaxLineSize] + "..."
	}
	output = output + lineBreak
	fmt.Print(output)
}
<|endoftext|>