ronantakizawa/codereview-bench huggingface dataset:
Repository: digitalocean/nginxconfig.io
File: src/nginxconfig/util/types_extensions.js (JavaScript)

Code before:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

export const gzipTypes = 'text/plain text/css text/xml application/json application/javascript application/rss+xml application/atom+xml image/svg+xml';

export const extensions = {
    assets: 'css(\\.map)?|js(\\.map)?',
    fonts: 'ttf|ttc|otf|eot|woff2?',
    svg: 'svgz?',
    images: 'jpe?g|png|gif|ico|cur|heic|webp|tiff?',
    audio: 'mp3|m4a|aac|ogg|midi?|wav',
    video: 'mp4|mov|webm|mpe?g|avi|ogv|flv|wmv',
    docs: 'pdf|' +
        'docx?|dotx?|docm|dotm|' +
        'xlsx?|xltx?|xlsm|xltm|' +
        'pptx?|potx?|pptm|potm|ppsx?',
    html: 'html',
};


Review comment (suggestion):
```suggestion
    html: 'html?',
```
Allow `html` or `htm`

Code after:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

export const gzipTypes = 'text/plain text/css text/xml application/json application/javascript application/rss+xml application/atom+xml image/svg+xml';

export const extensions = {
    assets: 'css(\\.map)?|js(\\.map)?',
    fonts: 'ttf|ttc|otf|eot|woff2?',
    svg: 'svgz?',
    images: 'jpe?g|png|gif|ico|cur|heic|webp|tiff?',
    audio: 'mp3|m4a|aac|ogg|midi?|wav',
    video: 'mp4|mov|webm|mpe?g|avi|ogv|flv|wmv',
    docs: 'pdf|' +
        'docx?|dotx?|docm|dotm|' +
        'xlsx?|xltx?|xlsm|xltm|' +
        'pptx?|potx?|pptm|potm|ppsx?',
    html: 'html?',
};
Repository: digitalocean/nginxconfig.io
File: src/nginxconfig/templates/footer.vue (Vue)

Code before:
                ></ExternalLink>,
                {{ $t('templates.footer.maintainedBy') }}
                <ExternalLink
                    :text="$t('templates.footer.digitalOcean')"
                    link="https://github.com/digitalocean/nginxconfig.io"
                ></ExternalLink>.
            </p>
        </div>
    </div>
</template>

<script>
    import ExternalLink from 'do-vue/src/templates/external_link';

    export default {
        name: 'Footer',
        components: {
            ExternalLink,
        },
        methods: {
            handleScrollToTop: () => {
                window.scrollTo({top: 0});

                const columns = document.querySelectorAll('.column-scroll-y');

                columns.forEach(column => column.scrollTo({top: 0}));
            },
        },
    };
</script>


Review comment (suggestion):
```suggestion
                window.scrollTo({ top: 0 });
                document.querySelectorAll('.column-scroll-y')
                  .forEach(column => column.scrollTo({ top: 0 }));
```
Also a nitpick, formatting + removing the redundant const (lmk if eslint disagrees with this)

Code after:
            </p>
            <p>
                {{ $t('templates.footer.originallyCreatedBy') }}
                <ExternalLink
                    :text="$t('templates.footer.balintSzekeres')"
                    link="https://b4lint.hu/"
                ></ExternalLink>,
                {{ $t('templates.footer.maintainedBy') }}
                <ExternalLink
                    :text="$t('templates.footer.digitalOcean')"
                    link="https://github.com/digitalocean/nginxconfig.io"
                ></ExternalLink>.
            </p>
        </div>
    </div>
</template>

<script>
    import ExternalLink from 'do-vue/src/templates/external_link';

    export default {
        name: 'Footer',
        components: {
            ExternalLink,
        },
        methods: {
            handleScrollToTop: () => {
                window.scrollTo({top: 0});

                document.querySelectorAll('.column-scroll-y')
                    .forEach(column => column.scrollTo({ top: 0 }));
            },
        },
    };
</script>
Repository: docker/compose
File: pkg/compose/compose.go (Go)

Code before:
				Name:   serviceLabel,
				Image:  c.Image,
				Labels: c.Labels,
			}
		}
		set[serviceLabel].Scale++
	}
	for _, service := range set {
		dependencies := service.Labels[api.DependenciesLabel]
		if len(dependencies) > 0 {
			service.DependsOn = types.DependsOnConfig{}
			for _, dc := range strings.Split(dependencies, ",") {
				dcArr := strings.Split(dc, ":")
				condition := ServiceConditionRunningOrHealthy
				// Let's restart the dependency by default if we don't have the info stored in the label
				restart := true
				required := true
				dependency := dcArr[0]

				// backward compatibility
				if len(dcArr) > 1 {
					condition = dcArr[1]
					if len(dcArr) > 2 {
						restart, _ = strconv.ParseBool(dcArr[2])
					}
					if len(dcArr) > 3 {
						required, _ = strconv.ParseBool(dcArr[3])
					}
				}
				service.DependsOn[dependency] = types.ServiceDependency{Condition: condition, Restart: restart, Required: required}
			}
		}
		project.Services = append(project.Services, *service)
	}
SERVICES:
	for _, qs := range services {
		for _, es := range project.Services {
			if es.Name == qs {
				continue SERVICES
			}
		}
		return project, errors.Wrapf(api.ErrNotFound, "no such service: %q", qs)
	}
	err := project.ForServices(services)
	if err != nil {
		return project, err
	}

	return project, nil
}


Review comment (suggestion):
this block is for backward compatibility only, I don't think we should extend syntax to support a 3rd argument

Code after:
				Name:   serviceLabel,
				Image:  c.Image,
				Labels: c.Labels,
			}
		}
		set[serviceLabel].Scale++
	}
	for _, service := range set {
		dependencies := service.Labels[api.DependenciesLabel]
		if len(dependencies) > 0 {
			service.DependsOn = types.DependsOnConfig{}
			for _, dc := range strings.Split(dependencies, ",") {
				dcArr := strings.Split(dc, ":")
				condition := ServiceConditionRunningOrHealthy
				// Let's restart the dependency by default if we don't have the info stored in the label
				restart := true
				required := true
				dependency := dcArr[0]

				// backward compatibility
				if len(dcArr) > 1 {
					condition = dcArr[1]
					if len(dcArr) > 2 {
						restart, _ = strconv.ParseBool(dcArr[2])
					}
				}
				service.DependsOn[dependency] = types.ServiceDependency{Condition: condition, Restart: restart, Required: required}
			}
		}
		project.Services = append(project.Services, *service)
	}
SERVICES:
	for _, qs := range services {
		for _, es := range project.Services {
			if es.Name == qs {
				continue SERVICES
			}
		}
		return project, errors.Wrapf(api.ErrNotFound, "no such service: %q", qs)
	}
	err := project.ForServices(services)
	if err != nil {
		return project, err
	}

	return project, nil
}

func (s *composeService) actualVolumes(ctx context.Context, projectName string) (types.Volumes, error) {
	opts := volume.ListOptions{
		Filters: filters.NewArgs(projectFilter(projectName)),
Repository: docker/compose
File: cmd/compose/scale.go (Go)

Code before:
	}

	for key, value := range serviceReplicaTuples {
		for i, service := range project.Services {
			if service.Name != key {
				continue
			}
			if service.Deploy == nil {
				service.Deploy = &types.DeployConfig{}
			}
			scale := uint64(value)
			service.Deploy.Replicas = &scale
			project.Services[i] = service
			break
		}
	}

	return backend.Scale(ctx, project, api.ScaleOptions{Services: services})
}

func parseServicesReplicasArgs(args []string) (map[string]int, error) {
	serviceReplicaTuples := map[string]int{}
	for _, arg := range args {
		key, val, ok := strings.Cut(arg, "=")
		if !ok || key == "" || val == "" {
			return nil, errors.Errorf("Invalide scale specifier %q.", arg)
		}
		intValue, err := strconv.Atoi(val)

		if err != nil {
			return nil, errors.Errorf("Invalide scale specifier, can't parse replicate value to int %q.", arg)
		}
		serviceReplicaTuples[key] = intValue
	}
	return serviceReplicaTuples, nil
}


Review comment (suggestion):
```suggestion
			return nil, errors.Errorf("invalid scale specifier: %s", arg)
```

Code after:
	}

	for key, value := range serviceReplicaTuples {
		for i, service := range project.Services {
			if service.Name != key {
				continue
			}
			if service.Deploy == nil {
				service.Deploy = &types.DeployConfig{}
			}
			scale := uint64(value)
			service.Deploy.Replicas = &scale
			project.Services[i] = service
			break
		}
	}

	return backend.Scale(ctx, project, api.ScaleOptions{Services: services})
}

func parseServicesReplicasArgs(args []string) (map[string]int, error) {
	serviceReplicaTuples := map[string]int{}
	for _, arg := range args {
		key, val, ok := strings.Cut(arg, "=")
		if !ok || key == "" || val == "" {
			return nil, errors.Errorf("invalid scale specifier: %s", arg)
		}
		intValue, err := strconv.Atoi(val)

		if err != nil {
			return nil, errors.Errorf("invalid scale specifier: can't parse replica value as int: %v", arg)
		}
		serviceReplicaTuples[key] = intValue
	}
	return serviceReplicaTuples, nil
}
Repository: docker/compose
File: cmd/compose/scale.go (Go)

Code before:
				continue
			}
			if service.Deploy == nil {
				service.Deploy = &types.DeployConfig{}
			}
			scale := uint64(value)
			service.Deploy.Replicas = &scale
			project.Services[i] = service
			break
		}
	}

	return backend.Scale(ctx, project, api.ScaleOptions{Services: services})
}

func parseServicesReplicasArgs(args []string) (map[string]int, error) {
	serviceReplicaTuples := map[string]int{}
	for _, arg := range args {
		key, val, ok := strings.Cut(arg, "=")
		if !ok || key == "" || val == "" {
			return nil, errors.Errorf("Invalide scale specifier %q.", arg)
		}
		intValue, err := strconv.Atoi(val)

		if err != nil {
			return nil, errors.Errorf("Invalide scale specifier, can't parse replicate value to int %q.", arg)
		}
		serviceReplicaTuples[key] = intValue
	}
	return serviceReplicaTuples, nil
}


Review comment (suggestion):
```suggestion
			return nil, errors.Errorf("invalid scale specifier: can't parse replica value as int: %v", arg)
```

Code after:
				continue
			}
			if service.Deploy == nil {
				service.Deploy = &types.DeployConfig{}
			}
			scale := uint64(value)
			service.Deploy.Replicas = &scale
			project.Services[i] = service
			break
		}
	}

	return backend.Scale(ctx, project, api.ScaleOptions{Services: services})
}

func parseServicesReplicasArgs(args []string) (map[string]int, error) {
	serviceReplicaTuples := map[string]int{}
	for _, arg := range args {
		key, val, ok := strings.Cut(arg, "=")
		if !ok || key == "" || val == "" {
			return nil, errors.Errorf("invalid scale specifier: %s", arg)
		}
		intValue, err := strconv.Atoi(val)

		if err != nil {
			return nil, errors.Errorf("invalid scale specifier: can't parse replica value as int: %v", arg)
		}
		serviceReplicaTuples[key] = intValue
	}
	return serviceReplicaTuples, nil
}
Repository: docker/compose
File: internal/tracing/keyboard_metrics.go (Go)

Code before:

   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 tracing

import (
	"context"

	"go.opentelemetry.io/otel/attribute"
)

func KeyboardMetrics(ctx context.Context, enabled, isDockerDesktopActive, isWatchConfigured, isDDComposeUI bool) {
	commandAvailable := []string{}
	if isDockerDesktopActive {
		commandAvailable = append(commandAvailable, "gui")
	}
	if isWatchConfigured {
		commandAvailable = append(commandAvailable, "watch")
	}

	if isDDComposeUI {
		commandAvailable = append(commandAvailable, "gui/composeview")
	}

	AddAttributeToSpan(ctx,
		attribute.Bool("navmenu.enabled", enabled),
		attribute.StringSlice("navmenu.command_available", commandAvailable))
}


Review comment (suggestion):
```suggestion
	if isDockerDesktopComposeUI {
```

Code after:

   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 tracing

import (
	"context"

	"go.opentelemetry.io/otel/attribute"
)

func KeyboardMetrics(ctx context.Context, enabled, isDockerDesktopActive, isWatchConfigured, isDockerDesktopComposeUI bool) {
	commandAvailable := []string{}
	if isDockerDesktopActive {
		commandAvailable = append(commandAvailable, "gui")
	}
	if isWatchConfigured {
		commandAvailable = append(commandAvailable, "watch")
	}

	if isDockerDesktopComposeUI {
		commandAvailable = append(commandAvailable, "gui/composeview")
	}

	AddAttributeToSpan(ctx,
		attribute.Bool("navmenu.enabled", enabled),
		attribute.StringSlice("navmenu.command_available", commandAvailable))
}
Repository: docker/compose
File: pkg/watch/dockerignore.go (Go)

Code before:
	if i.matcher.Exclusions() {
		for _, pattern := range i.matcher.Patterns() {
			if !pattern.Exclusion() {
				continue
			}
			if paths.IsChild(f, pattern.String()) {
				// Found an exclusion match -- we don't match this whole dir
				return false, nil
			}
		}
		return true, nil
	}
	return true, nil
}

func LoadDockerIgnore(repoRoot string) (*dockerPathMatcher, error) {
	absRoot, err := filepath.Abs(repoRoot)
	if err != nil {
		return nil, err
	}

	patterns, err := readDockerignorePatterns(absRoot)
	if err != nil {
		return nil, err
	}

	return NewDockerPatternMatcher(absRoot, patterns)
}

// Make all the patterns use absolute paths.
func absPatterns(absRoot string, patterns []string) []string {
	absPatterns := make([]string, 0, len(patterns))
	for _, p := range patterns {
		// The pattern parsing here is loosely adapted from fileutils' NewPatternMatcher
		p = strings.TrimSpace(p)
		if p == "" {
			continue
		}
		p = filepath.Clean(p)

		pPath := p
		isExclusion := false
		if p[0] == '!' {
			pPath = p[1:]
			isExclusion = true
		}

		if !filepath.IsAbs(pPath) {
			pPath = filepath.Join(absRoot, pPath)
		}
		absPattern := pPath

Review comment (suggestion):
Is `build.Dockerfile` always just the file name, or can it be an absolute path? (in that case, no need to join if with the repo-root)

Code after:

	// We match the dir, but we might exclude files underneath it.
	if i.matcher.Exclusions() {
		for _, pattern := range i.matcher.Patterns() {
			if !pattern.Exclusion() {
				continue
			}
			if paths.IsChild(f, pattern.String()) {
				// Found an exclusion match -- we don't match this whole dir
				return false, nil
			}
		}
		return true, nil
	}
	return true, nil
}

func LoadDockerIgnore(build *types.BuildConfig) (*dockerPathMatcher, error) {
	repoRoot := build.Context
	absRoot, err := filepath.Abs(repoRoot)
	if err != nil {
		return nil, err
	}

	// first try Dockerfile-specific ignore-file
	f, err := os.Open(filepath.Join(repoRoot, build.Dockerfile+".dockerignore"))
	if os.IsNotExist(err) {
		// defaults to a global .dockerignore
		f, err = os.Open(filepath.Join(repoRoot, ".dockerignore"))
		if os.IsNotExist(err) {
			return NewDockerPatternMatcher(repoRoot, nil)
		}
	}
	if err != nil {
		return nil, err
	}
	defer func() { _ = f.Close() }()

	patterns, err := readDockerignorePatterns(f)
	if err != nil {
		return nil, err
	}

	return NewDockerPatternMatcher(absRoot, patterns)
}

// Make all the patterns use absolute paths.
func absPatterns(absRoot string, patterns []string) []string {
	absPatterns := make([]string, 0, len(patterns))
	for _, p := range patterns {
		// The pattern parsing here is loosely adapted from fileutils' NewPatternMatcher
Repository: docker/compose
File: pkg/compose/generate.go (Go)

Code before:
	for _, containerName := range options.Containers {
		filtersListNames.Add("name", containerName)
		filtersListIDs.Add("id", containerName)
	}
	containers, err := s.apiClient().ContainerList(ctx, containerType.ListOptions{
		Filters: filtersListNames,
		All:     true,
	})
	if err != nil {
		return nil, err
	}

	containersByIds, err := s.apiClient().ContainerList(ctx, containerType.ListOptions{
		Filters: filtersListIDs,
		All:     true,
	})
	if err != nil {
		return nil, err
	}
	for _, container := range containersByIds {
		if !utils.Contains(containers, container) {
			containers = append(containers, container)
		}
	}

	return s.projectFromName(containers, options.Project.Name)
}


Review comment (suggestion):
`projectFromName` will search for compose labels and as such can't build a model from containers which have been explicitly created for this command, sounds to me this is a huge restriction for usability.
IMHO this command should create a service for each container passed as argument, and include volumes they refer to (+ a default network if there's no explicit one)

Code after:

func (s *composeService) Generate(ctx context.Context, options api.GenerateOptions) (*types.Project, error) {
	filtersListNames := filters.NewArgs()
	filtersListIDs := filters.NewArgs()
	for _, containerName := range options.Containers {
		filtersListNames.Add("name", containerName)
		filtersListIDs.Add("id", containerName)
	}
	containers, err := s.apiClient().ContainerList(ctx, containerType.ListOptions{
		Filters: filtersListNames,
		All:     true,
	})
	if err != nil {
		return nil, err
	}

	containersByIds, err := s.apiClient().ContainerList(ctx, containerType.ListOptions{
		Filters: filtersListIDs,
		All:     true,
	})
	if err != nil {
		return nil, err
	}
	for _, container := range containersByIds {
		if !utils.Contains(containers, container) {
			containers = append(containers, container)
		}
	}

	if len(containers) == 0 {
		return nil, fmt.Errorf("no container(s) found with the following name(s): %s", strings.Join(options.Containers, ","))
	}

	return s.createProjectFromContainers(containers, options.ProjectName)
}

func (s *composeService) createProjectFromContainers(containers []moby.Container, projectName string) (*types.Project, error) {
	project := &types.Project{}
	services := types.Services{}
	networks := types.Networks{}
	volumes := types.Volumes{}
	secrets := types.Secrets{}

	if projectName != "" {
		project.Name = projectName
	}

	for _, c := range containers {
		// if the container is from a previous Compose application, use the existing service name
		serviceLabel, ok := c.Labels[api.ServiceLabel]
		if !ok {
Repository: docker/compose
File: pkg/compose/convergence.go (Go)

Code before:
			opts := createOptions{
				AutoRemove:        false,
				AttachStdin:       false,
				UseNetworkAliases: true,
				Labels:            mergeLabels(service.Labels, service.CustomLabels),
			}
			container, err := c.service.createContainer(ctx, project, service, name, number, opts)
			updated[actual+i] = container
			return err
		}))
		continue
	}

	err = eg.Wait()
	c.setObservedState(service.Name, updated)
	return err
}

func (c *convergence) stopDependentContainers(ctx context.Context, project *types.Project, service types.ServiceConfig) error {
	// Stop dependent containers, so they will be restarted after service is re-created
	dependents := project.GetDependentsForService(service)
	err := c.service.stop(ctx, project.Name, api.StopOptions{
		Services: dependents,
		Project:  project,
	})
	return err

	for _, name := range dependents {
		dependents := c.getObservedState(name)
		for i, dependent := range dependents {
			dependent.State = ContainerExited
			dependents[i] = dependent
		}
		c.setObservedState(name, dependents)
	}
	return nil
}

func getScale(config types.ServiceConfig) (int, error) {
	scale := config.GetScale()
	if scale > 1 && config.ContainerName != "" {
		return 0, fmt.Errorf(doubledContainerNameWarning,
			config.Name,
			config.ContainerName)
	}
	return scale, nil
}

// resolveServiceReferences replaces reference to another service with reference to an actual container
func (c *convergence) resolveServiceReferences(service *types.ServiceConfig) error {
	err := c.resolveVolumeFrom(service)

Review comment (suggestion):
```suggestion
	if err != nil {
		return err
	}
```

Code after:
			opts := createOptions{
				AutoRemove:        false,
				AttachStdin:       false,
				UseNetworkAliases: true,
				Labels:            mergeLabels(service.Labels, service.CustomLabels),
			}
			container, err := c.service.createContainer(ctx, project, service, name, number, opts)
			updated[actual+i] = container
			return err
		}))
		continue
	}

	err = eg.Wait()
	c.setObservedState(service.Name, updated)
	return err
}

func (c *convergence) stopDependentContainers(ctx context.Context, project *types.Project, service types.ServiceConfig) error {
	// Stop dependent containers, so they will be restarted after service is re-created
	dependents := project.GetDependentsForService(service)
	err := c.service.stop(ctx, project.Name, api.StopOptions{
		Services: dependents,
		Project:  project,
	})
	if err != nil {
		return err
	}

	for _, name := range dependents {
		dependents := c.getObservedState(name)
		for i, dependent := range dependents {
			dependent.State = ContainerExited
			dependents[i] = dependent
		}
		c.setObservedState(name, dependents)
	}
	return nil
}

func getScale(config types.ServiceConfig) (int, error) {
	scale := config.GetScale()
	if scale > 1 && config.ContainerName != "" {
		return 0, fmt.Errorf(doubledContainerNameWarning,
			config.Name,
			config.ContainerName)
	}
	return scale, nil
}

// resolveServiceReferences replaces reference to another service with reference to an actual container